USACO Runaround Numbers

Code

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
59
/*
ID: wcr19961
PROG: runround
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn = 10;
int b[maxn];
bool vis[maxn];
bool check(int n) {
int len = 0;
memset(vis, 0, sizeof vis);
while (n) {
b[len] = n % 10;
if (n % 10 == 0 || vis[n % 10]) {
return false;
}
vis[b[len]] = true;
++len;
n /= 10;
}
int p = len - 1;
for (int i = 0; i < len; ++i) {
vis[b[p]] = false;
p = ((p - b[p]) % len + len) % len;
}
if (p != len - 1) {
return false;
}
for (int i = 0; i < 10; ++i) {
if (vis[i]) {
return false;
}
}
return true;
}
int main() {
freopen("runround.in", "r", stdin);
freopen("runround.out", "w", stdout);
int n;
scanf("%d", &n);
for (;;) {
if (check(++n)) {
printf("%d\n", n);
return 0;
}
}
return 0;
}