zoukankan      html  css  js  c++  java
  • poj 1426 Find The Multiple

    题意:write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1。写一个程序找出一个是n的倍数且只包含0,1的m

     

    看了别人的代码,觉得他的思想特别好,由于bFS所以每次进队列的数是固定的第一个是1,第二个是10,第三个是11,第四个是110,通过推倒可知道,它是很规则的按顺序增长的,所以只要知道,进了i次队列使余数为0,则可以通过i求出、

    #include<stdio.h>
    const int MAXN=600000;
    int mod[MAXN];
    int main()
    {
    
        int i,n;
        while(scanf("%d",&n) && n)
        {
            mod[1]=1%n;
            for(i=2;mod[i-1]!=0;i++)
                mod[i]=(mod[i/2]*10+i%2)%n;//i%2可以控制+1或+0
               //100的前一个是10,不是1000的前一个是100,又因为这是双口BFS,所以i/2
             int cas=0;
             i--;
             while(i)
             {
                 mod[cas++]=i%2;
                 i/=2;
             }
             for(i=cas-1;i>=0;i--)
               printf("%d",mod[i]);
             printf("\n");
        }
    }

     

    #include<stdio.h>
    #include<queue>
    #include<string.h>
    using namespace std;
    
    const int MAXN= 100010;
    int step[MAXN],vis[MAXN];
    queue<int>Q;
    int BFS(int n,int k)
    {
        memset(step,0,sizeof(step));
        memset(vis,0,sizeof(vis));
        int head,next;
        step[n]=0;
        vis[n]=1;
        Q.push(n);
        while(!Q.empty())
        {
            head=Q.front();
            Q.pop();
            for(int i=0;i<3;i++)
            {
                if(i==0) next=head-1;
                if(i==1) next=head*2;
                if(i==2) next=head+1;
                if(next>MAXN || next<0) continue;
                if(!vis[next])
                {
                    Q.push(next);
                    vis[next]=1;
                    step[next]=step[head]+1;
                }
                if(next==k) return step[next];
            }
        }
    }
    
    int main()
    {
        int n,k;
        while(scanf("%d%d",&n,&k)!=EOF)
        {
            int ans=BFS(n,k);
            printf("%d\n",ans);
        }
        return 0;
    }

     

     

  • 相关阅读:
    php获取随机字符串
    php短网址生成算法
    tp5.1发送邮件
    PHP简单 对象(object) 与 数组(array) 的转换
    PHP获取接下来一周的日期
    swoole 连接池
    PHP静态文件缓存
    php微信分享demo
    生成二维码并指定地址跳转
    tp5依赖注入(自动实例化):解决了像类中的方法传对象的问题
  • 原文地址:https://www.cnblogs.com/zsboy/p/2646456.html
Copyright © 2011-2022 走看看