-
Notifications
You must be signed in to change notification settings - Fork 2
/
Minimal Rotation.cpp
83 lines (72 loc) · 1.91 KB
/
Minimal Rotation.cpp
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
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
#define ll long long
struct SuffixAuto {
struct State {
int len, link;
int next[26];
State(int _len = 0, int _link = -1) : len(_len), link(_link) {
memset(next, -1, sizeof(next));
}
};
vector<State> states;
int last;
SuffixAuto() {}
SuffixAuto(const string &S) {
init(S);
}
inline int state(int len = 0, int link = -1) {
states.emplace_back(len, link);
return states.size() - 1;
}
void init(const string &S) {
states.reserve(2 * S.size());
last = state();
for (char c : S)
extend(c);
}
void extend(char _c) {
int c = _c - 'a'; // change for different alphabet
int cur = state(states[last].len + 1), P = last;
while (P != -1 && states[P].next[c] == -1) {
states[P].next[c] = cur;
P = states[P].link;
}
if (P == -1)
states[cur].link = 0;
else {
int Q = states[P].next[c];
if (states[P].len + 1 == states[Q].len)
states[cur].link = Q;
else {
int C = state(states[P].len + 1, states[Q].link);
copy(states[Q].next, states[Q].next + 26, states[C].next);
while (P != -1 && states[P].next[c] == Q) {
states[P].next[c] = C;
P = states[P].link;
}
states[Q].link = states[cur].link = C;
}
}
last = cur;
}
};
string S;
SuffixAuto sa;
int main(){
string s;
cin>>s;
int n = s.size();
s = s+s;
sa.init(s);
int u = 0;
for(int i=0;i<n;i++){
for(int j=0;j<26;j++){
if( sa.states[u].next[j]!=-1 ){
u = sa.states[u].next[j];
cout<<(char)(j+'a');
break;
}
}
}
}