原题:
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 Input2
6
19
0
Sample Output
10
100100100100100100
111111111111111111
大致题意:输入一个数,输出一个每一位均由0和1构成、并且可以整除输入数字的数。
思路:从第1数位到第n数位BFS
注意取模需要优化时间不然可能TLE;
优化方式参考高精度取模,这样取模的时间复杂度可达到O(1);
int qmod(char s[300],int mod){
int len = strlen(s);
int sum = 0;
for(int i=1;i<=len;i--){
sum = (sum*10+s[i]-'0')%mod;//关键公式
}
return sum;//模数
}
在路径方面我们用数组
pre[i][j][k] //i 第i数位 j 该位是0还是1 k目前所取的模数
另外输出时
我们需要开一个栈实现逆序输出
代码贴示如下
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<algorithm>
#define ll long long
using namespace std;
char s[300];
int qmod(char s[300],int mod){
int len = strlen(s);
int sum = 0;
for(int i=1;i<=len;i--){
sum = (sum*10+s[i]-'0')%mod;
}
return sum;//模数
}
struct node{
int i;//第几位
bool j;
int mod;
};
int main()
{
while(1){
int mod;
cin>>mod;
if(mod==0) break;
queue<node>q;
node pre[101][2][201];
q.push((node){1,1,1});
node k;
while(!q.empty()){
node y = q.front();
q.pop();
if(y.mod==0){
k = y;
// cout<<k.i<<k.j<<endl;
break;
}
// node next = y;
if(y.i<100){
q.push((node){y.i+1,1,(y.mod*10+1)%mod});
q.push((node){y.i+1,0,(y.mod*10)%mod});
pre[y.i+1][1][(y.mod*10+1)%mod] = y;
pre[y.i+1][0][(y.mod*10)%mod] = y;
}
}
stack<node>s;
s.push(k);
// cout<<"1";
while(1){
node f = s.top();
if(pre[f.i][f.j][f.mod].i==0&&pre[f.i][f.j][f.mod].j==0&&pre[f.i][f.j][f.mod].mod==0)
break;
s.push(pre[f.i][f.j][f.mod]);
}
while(!s.empty()){
node p = s.top();
cout<<p.j;
s.pop();
}
cout<<endl;
// cout<<pre[f.i][f.j][f.mod].j;
}
}