#include <iostream>
#include <climits>
#include <queue>
#include <stack>
using namespace std;
const int maxn = 10000 + 5;
struct {
char val; //last digit 0 or 1, -1 for illegal
int prev;
} a[maxn];
int Queue[maxn];
int * const Stack = Queue;
int main()
{
int n;
while (scanf("%d", &n) != EOF){
if (n == 0){
printf("0\n");
continue;
}
//init
for (int i = 0; i < n; i++){
a[i].val = -1;
}
a[1 % n].val = '1';
a[1 % n].prev = -1;
int *Base, *Top;
Base = Top = Queue;
*Top++ = 1;
while (Base != Top && a[0].val == -1){
int x = *Base++;
int y = (x * 10) % n;
if (a[y].val == -1){
a[y].val = '0';
a[y].prev = x;
*Top++ = y;
}
int z = y + 1;
if (z >= n) z -= n;
if (a[z].val == -1){
a[z].val = '1';
a[z].prev = x;
*Top++ = z;
}
}
Base = Top = Stack;
int x = 0;
do {
*Top++ = a[x].val;
x = a[x].prev;
} while (x != -1);
while (Base != Top){
putchar(*--Top);
}
putchar('\n');
}
return 0;
}
这代码能AC
供大家参考