-
Notifications
You must be signed in to change notification settings - Fork 41
/
suffix_automaton.cpp
99 lines (79 loc) · 1.8 KB
/
suffix_automaton.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
const int MAXN = (1 << 20);
struct suffix_automaton {
map<char, int> to[MAXN];
int len[MAXN], link[MAXN];
int last, psz = 0;
void add_letter(char c) {
int p = last, cl, q;
if(to[p].count(c)) {
q = to[p][c];
if(len[q] == len[p] + 1) {
last = q;
return;
}
cl = psz++;
len[cl] = len[p] + 1;
to[cl] = to[q];
link[cl] = link[q];
link[q] = cl;
last = cl;
for(; to[p][c] == q; p = link[p]) {
to[p][c] = cl;
}
return;
}
last = psz++;
len[last] = len[p] + 1;
for(; to[p][c] == 0; p = link[p]) {
to[p][c] = last;
}
if(to[p][c] == last) {
link[last] = p;
return;
}
q = to[p][c];
if(len[q] == len[p] + 1) {
link[last] = q;
return;
}
cl = psz++;
len[cl] = len[p] + 1;
to[cl] = to[q];
link[cl] = link[q];
link[q] = cl;
link[last] = cl;
for(; to[p][c] == q; p = link[p]) {
to[p][c] = cl;
}
}
void clear() {
for(int i = 0; i < psz; i++) {
len[i] = 0, link[i] = 0, to[i].clear();
}
psz = 1;
last = 0;
}
void init(string s) {
clear();
for(int i = 0; i < (int)s.size(); i++) {
add_letter(s[i]);
}
}
suffix_automaton() {
psz = 0;
clear();
}
};
void read() {}
suffix_automaton sa;
void solve() { sa.clear(); }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
read();
solve();
return 0;
}