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.
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.
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.
2 6 19 0
10 100100100100100100111111111111111111
思路1 dfs :因为结果是n的倍数,所以必须有一个因子x,x*n = m;那么模拟乘法,留下最后一位,只不过最后一位只能是0或1,维护剩余的进位dat,当dat = 1 时,乘法就算完了。具体就是先对n处理一下,把后面的0去掉,并存起来。 for(i : 0 - 9) ,如果n*i+dat个位是 1 或 0,满足题意, 那么dat/=10,并且记录一下个位的值。例如:n = 6,则第一步:dat = 0, dat+ n*5 末尾是0 更新 dat = 3保留 ans【k++】 = 0,第二步,dat= 3 dat+n*3末位是1,更新dat = 2 第三步回到上个例子;注意要剪枝,dat不可重复出现不然死循环。
#include <cstdio> #include <queue> #include <map> #include <climits> #include <cstring> #include <iostream> using namespace std; int ans[150];//记录最终结果 map <int,int> a; // 标记dat是否有过. int n; bool ok; void dfs(int dat,int k) { if(ok || k > 50) return; // K不要取到100,可能会超内存,本来想分梯度,但是改了下50,竟然就过了 if(dat == 1) { ans[k] = dat; for(int i = k; i >=0; i--) printf("%d",ans[i]); printf("\n"); ok = 1; return; } for(int i = 0; i <= 9; i++) { if(((dat+n*i) % 10 ) / 2 == 0) { int tmp; ans[k] = (dat+n*i) % 10; tmp = (dat+n*i)/10; if(a[tmp]) continue; a[tmp] = 1; dfs(tmp,k+1); a[tmp] = 0; } } } int main() { while(scanf("%d",&n)&&n) { a.clear(); a[0] = 1,ok=0; int k = 0; while((n%10) == 0) { ans[k++] = 0; n/=10; } if(n == 1) { ans[k] = 1; for(int i = k; i >=0; i--) printf("%d",ans[i]); printf("\n"); continue; } dfs(0,k); } return 0; }
后来见了个代码,直接bfs n 多花点时间应该也能过,试了试真过了,真是蒙了。
#include<cstdio> #include<vector> using namespace std; int find; void dfs(unsigned long long t,int n,int k) { if(find)return; if(t%n==0) { printf("%I64u\n",t); find=1; return; } if(k==19) return ; dfs(t*10,n,k+1); dfs(t*10+1,n,k+1); } int main() { int n; while(scanf("%d",&n),n) { find=0; dfs(1,n,0); } return 0; }