-
Notifications
You must be signed in to change notification settings - Fork 11
/
SPOJ370.cc
58 lines (53 loc) · 1.1 KB
/
SPOJ370.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// SPOJ 370: Ones and zeros
// http://www.spoj.com/problems/ONEZERO/
//
// solution: BFS (the number of states is at most x).
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <queue>
#include <functional>
#include <algorithm>
using namespace std;
#define fst first
#define snd second
#define all(c) c.begin(), c.end()
void solve(int x) {
if (x <= 1) {
printf("%d\n", x);
return;
}
vector<int> prev(x), path(x);
queue<int> que;
que.push(1);
prev[1] = -1;
path[1] = 1;
while (!que.empty() && prev[0] == 0) {
int a = que.front(); que.pop();
for (int d = 0; d <= 1; ++d) {
int b = (10 * a + d) % x;
if (prev[b] == 0) {
prev[b] = a;
path[b] = d;
que.push(b);
}
}
}
vector<int> ans;
for (int a = 0; a >= 0; a = prev[a])
ans.push_back(path[a]);
for (int i = ans.size()-1; i >= 0; --i)
printf("%d", ans[i]);
printf("\n");
}
int main() {
int ncase;
scanf("%d", &ncase);
for (int icase = 0; icase < ncase; ++icase) {
int x;
scanf("%d", &x);
solve(x);
}
}