题目名称:Find The Multiple
题目链接:http://poj.org/problem?id=1426
Description
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2 6 19 0
Sample Output
10 100100100100100100 111111111111111111
题意:给出一个整数n,(1 <= n <= 200)。求出任意一个它的倍数m,要求m必须只由十进制的'0'或'1'组成。
思路:bfs+同余模,因为会出现大数问题,所以用同余模可以解决,
代码如下:
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int n;
struct Node //将该数表示二进制时记为x,该数表示十进制时记为mod
{
int x,mod;
};
int a[1000000];
queue<Node> q;
int bfs()
{
while(!q.empty())
q.pop();
Node now;
now.x=1;
now.mod=1;
q.push(now);
while(!q.empty())
{
Node d=q.front();
q.pop();
Node tmp;
tmp.x=d.x<<1;
tmp.mod=d.mod*10%n;
q.push(tmp);
if(tmp.mod==0)
return tmp.x;
tmp.x=(d.x<<1)+1;
tmp.mod=(d.mod*10+1)%n;
q.push(tmp);
if(tmp.mod==0)
return tmp.x;
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i;
if(n==0)
break;
/* a[1]=1%n;
for(i=2;a[i-1]!=0;i++)
a[i]=(a[i>>1]*10+i%2)%n; //把二进制取模的结果存在数组里,下标的二进制是要求的十进制
i--;*/
int s=0;
i=bfs();
while(i) //把*10操作转化为%2操作,逆向求倍数的每一位数字
{
a[s++]=i%2;
i=i>>1;
}
while(s)
printf("%d",a[--s]);
printf("\n");
}
return 0;
}