题解报告:poj 1426 Find The Multiple(bfs、dfs)

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的10进制数x,x只由1和0组成,并且满足x%n==0,输出这个x即可。由于x只由0和1组成,因此容易想到构建一棵平衡二叉树,从根节点值为1开始,每个左节点的值都为父节点值的10倍,每个右节点的值都为父节点值的10倍加1,这样只要找到x%n==0即可。亲测了一下x的值在long long范围内,于是bfs或dfs暴力即可。
AC代码之bfs:
 1 #include<iostream>
 2 #include<queue>
 3 #include<cstdio>
 4 using namespace std;
 5 typedef long long LL;LL n;
 6 queue<LL> que;
 7 void bfs(LL n){//在long long的范围内查找,按层遍历
 8     while(!que.empty())que.pop();//清空
 9     que.push(1LL);//模拟一棵平衡二叉树,先将入根节点的值1入队
10     while(!que.empty()){
11         LL x=que.front();que.pop();
12         if(x%n==0){cout<<x<<endl;return;}//只要满足条件,立即退出
13         que.push(x*10);//左节点的值为父节点值的10倍
14         que.push(x*10+1);//右节点的值为父节点值的10倍加1
15     }
16 }
17 int main(){
18     while(cin>>n&&n){bfs(n);}
19     return 0;
20 }

AC代码之dfs:

 1 #include<iostream>
 2 #include<queue>
 3 #include<cstdio>
 4 using namespace std;
 5 typedef long long LL;LL n;bool flag;
 6 void dfs(int num,LL x,LL n){
 7     if(num>19||flag)return;//如果x的位数num超过19位即溢出了long long 范围,直接返回到上一层;如果已找到即flag为true则一直回退,直到栈空,表示不再深搜下去
 8     if(x%n==0){cout<<x<<endl;flag=true;return;}
 9     dfs(num+1,x*10,n);//左递归
10     dfs(num+1,x*10+1,n);//右递归
11 }
12 int main(){
13     while(cin>>n&&n){flag=false;dfs(1,1,n);}//从位数1,根节点值为1开始深搜
14     return 0;
15 }
原文地址:https://www.cnblogs.com/acgoto/p/9435346.html