Find The Multiple POJ - 1426

原题链接

考察:dfs或者bfs

暴力枚举即可,没有什么特别的技巧

dfs:找到了就标记一下,避免继续搜索(因为答案一定在long long里,所以超过18位就可以不用算了)

bfs:用G++编译,找到当即退出.注意一定要让所有路径都有返回值否则报错

 1 #include <cstdio>
 2 #include <iostream>
 3 using namespace std;
 4 typedef long long ll;
 5 int n;
 6 bool flag;
 7 void dfs(int step,ll y)
 8 {
 9     if(step>19 || flag==1)//利用flag保证找到这个数的时候终止
10         return;//long long最多18位,所以要到19终止 
11     if(y%n==0)
12     {
13         flag=1;
14         cout << y << endl;
15         return;
16     }
17     dfs(step+1,y*10);//两个方向
18     dfs(step+1,y*10+1);
19 }
20 int main()
21 {
22     while(scanf("%d",&n)!=EOF&&n){
23         flag = false;
24         dfs(1,1);
25     }
26     return 0;
27 }
dfs
 1 #include <iostream>
 2 #include <queue>
 3 #include <cstdio>
 4 using namespace std;
 5 typedef unsigned long long ull;
 6 int n;
 7 ull h[210];
 8 ull bfs(int x)
 9 {
10     queue<ull> q;
11     q.push(1);
12     while(!q.empty()){
13         ull tmp = q.front();
14         q.pop();
15         if(tmp%x==0) return tmp;
16         q.push(tmp*10);
17         q.push(tmp*10ull+1);
18     }
19     return 0;
20 }
21 int main()
22 {
23     for(int i=1;i<=200;i++)
24         h[i] = bfs(i);
25     while(scanf("%d",&n)!=EOF&&n)
26          printf("%llu\n",h[n]);
27     return 0;
28 }
bfs

 

posted @ 2021-01-08 22:09  acmloser  阅读(55)  评论(0编辑  收藏  举报