Find The Multiple
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 27988 | Accepted: 11621 | Special Judge |
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
挺难想到用bfs的,长度最长为100的数很容易往大数方向想。
想到用bfs对当前序列的后面添加0或1,直到当前序列取模为0。
再想到用同余模定理后就可以转化为将当前序列的模入队,之后只要在出队的模后添0或1后再取模入队,直到模为0。
不过新的问题在于如何把大数保存并输出。
可以发现事实上这道题的bfs是在对一棵节点只有0或1分支的二叉树作层次遍历。
所以我们可以根据二叉树的性质用存进队列的所有模(用一个数组保存)来输出大数的每一位。
具体看代码。
然后这道题如果用STL的queue,用C++编译是会TLE的,自己用数组实现的队列则不会,或者用G++编译也不会。
不过用STL的queue速度会慢上不少,我猜测可能部分时间用去分配空间了,毕竟自己用数组实现的话,数组也要开到百万以上。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <stack> #include <bitset> #include <queue> #include <set> #include <map> #include <string> #include <algorithm> #define FOP freopen("data.txt","r",stdin) #define inf 0x3f3f3f3f #define maxn 1000010 #define mod 1000000007 #define PI acos(-1.0) #define LL long long using namespace std; int m; int mods[maxn]; int ans[110]; int cot; void bfs() { queue<int> Q; Q.push(1); while(!Q.empty()) { int t = Q.front(); mods[cot++] = t; Q.pop(); if(t == 0) break; int t1 = (t * 10 + 0) % m; int t2 = (t * 10 + 1) % m; Q.push(t1); Q.push(t2); } } int main() { while(scanf("%d", &m) && m) { cot = 1; int n = 0; bfs(); cot--; while(cot) { ans[n++] = cot % 2; cot /= 2; } for(int i = n - 1; i >= 0; i--) printf("%d", ans[i]); printf("\n"); } return 0; }