Find The Multiple
Time Limit: 1000MS | Memory Limit: 10000K | |||
Total Submissions: 19305 | Accepted: 7831 | 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也已经有一段时间了,说实话,与其说这是博客,还不如说是我的个人日志比较恰当。
前面应该发表过同一道题目的另外一种解法,参考一位前辈的很有趣的解法,这里我想写写一般传统的做法,虽然代码长度较长,但是占用内存少,时间快,这些都是很明显优越的地方,看着这些前辈的神一般的方法,深深感觉到,“路漫漫其修远兮,吾将上下而求索”。
不说废话了,再说下去可能就没有地方来放代码了。(我语文功底还是不错的,呵呵!)
以下是AC代码,一如既往还是用C语言实现的:
#include <stdio.h> #include <math.h> #include <string.h> #define maxn 999999 int n; int flag[200]; int ans[200]; struct node { int k,temp,last; }num[maxn],cur; int bfs() { int top,end; top=end=0; cur.k=1; cur.temp=1%n; cur.last=-1; flag[cur.temp]=1; num[top++]=cur; while(top>=end) { cur=num[end]; end++; if(!cur.temp) return end-1; if(!flag[(cur.temp*10+1)%n]) { num[top].k=1; num[top].temp=(cur.temp*10+1)%n; flag[(cur.temp*10+1)%n]=1; num[top++].last=end-1; } if(!flag[cur.temp*10%n]) { num[top].k=0; num[top].temp=cur.temp*10%n; flag[cur.temp*10%n]=1; num[top++].last=end-1; } } return -1; } int main() { while(~scanf("%d",&n),n) { memset(flag,0,sizeof(flag)); int j=bfs(); int i=0; while(j!=-1) { //printf("%d",num[j].k); ans[i++]=num[j].k; j=num[j].last; } for(int t=i-1;t>=0;t--) printf("%d",ans[t]); printf("\n"); } return 0; }