poj-1426-bfs取余

来源:互联网 发布:java常见类 编辑:程序博客网 时间:2024/05/16 17:45

题意:

给一个数n,让你找出一个只有1,0,组成的十进制数,要求是找到的数可以被n整除。

做法:

假如n=6;

1余n=1;

10余n=1*10%6=4;

11余n=(1*10+1)%6=5;

100余n=4*10%6=4;

101余n=(4*10+1)%6=5;

110余n=5*10%6=2;

111余n=(5*10+1)%6=3;

可以推知10。。。。01余n=(10。。。。0余n*10+1)余n;

#include<iostream>#include<stdio.h>#include<queue>using namespace std;void bfs(int n){    queue<long long>q;    q.push(1);    while(!q.empty())    {        int i;        long long x;        x=q.front();        q.pop();        if(x%n==0)        {            printf("%lld\n",x);            return ;        }        q.push(x*10);        q.push(x*10+1);    }}int main(){    int n;    while(scanf("%d",&n)&&n)    {        bfs(n);    }    return 0;}


原创粉丝点击