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);
	}
}

posted @   unique_pursuit  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示