0
点赞
收藏
分享

微信扫一扫

D - Find The Multiple(找到倍数)——bfs搜索

Find The Multiple

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(n<=200),找一个非零倍数m,他的十进制数是由0和1组成的,找出m的值。

解题思路:由于n不为0,则我们可以确定非零倍数m的起始位数可以为1,那么接下来可以在后面位数添0或1两种步骤,即不断更新(x10)或(x10+1),我们可以利用bfs搜索解决此问题,而这里有个细节就是不用设置辅助数组标志访问(因为每个结果都不一样)。

AC代码:

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdlib>


using namespace std;

long long n;

void bfs(long long n)//通过bfs来寻求最短路径。 此题不用设置标志数组,因为每个结果都不一样。
{
queue<long long> Q;
long long head,temp;
head=1;
Q.push(head);
while(!Q.empty())
{
head=Q.front();
Q.pop();
for(int i=0;i<2;i++) //二种步骤
{
if(i==0)temp=head*10;
else if(i==1)temp=head*10+1;
Q.push(temp);
if(temp%n==0){cout<<temp<<endl;return;}
}
}
return ;
}
int main()
{
while(cin>>n&&n!=0)
{
bfs(n);
}
}


举报

相关推荐

0 条评论