UVa 517 - Word

链接

传送门

题意

给出一个由’a’和’b’组成的字符串及八种变化方式,输出变化$s$次之后的字符串的最小字典序形式。

思路

长度最大为15,可以模拟出所有字符串,找出周期。

代码

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
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
char str[20], c[10][5];
int n, s;
map<string, int> m;
string Next(string x) {
string res = x;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < n; ++j) {
bool ok = true;
for (int k = 0; k < 3; ++k) {
int p = k == 0 ? -2 : -1;
p = (n + j + k + p) % n;
if (x[p] != c[i][k]) {
ok = false;
break;
}
}
if (ok) {
res[j] = c[i][3];
}
}
}
return res;
}
int main() {
while (~scanf("%d", &n)) {
m.clear();
scanf("%s", str);
for (int i = 0; i < 8; ++i) {
scanf("%s", c[i]);
}
scanf("%d", &s);
string tmp = str;
m[tmp] = 0;
int cnt = 0, cnt2 = 0;
for (;;) {
++cnt;
tmp = Next(tmp);
if (m.count(tmp)) {
cnt2 = m[tmp];
break;
}
m[tmp] = cnt;
}
if (s >= cnt) {
s -= cnt;
s %= (cnt - cnt2);
} else {
tmp = str;
}
while (s--) {
tmp = Next(tmp);
}
string ans = tmp;
tmp += tmp;
for (int i = 0; i < n; ++i) {
if (tmp.substr(i, n) < ans) {
ans = tmp.substr(i, n);
}
}
puts(ans.c_str());
}
return 0;
}