-
Notifications
You must be signed in to change notification settings - Fork 521
/
suffix-automaton.cpp
60 lines (54 loc) · 1.52 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
#include <bits/stdc++.h>
using namespace std;
// https://cp-algorithms.com/string/suffix-automaton.html
struct state {
int length;
int suffLink;
vector<int> inv_sufflinks;
int firstPos = -1;
vector<int> next = vector<int>(128, -1);
};
constexpr int MAXLEN = 100'000;
state st[MAXLEN * 2];
int sz;
void build_suffix_automaton(const string &s) {
st[0].suffLink = -1;
int last = 0;
sz = 1;
for (int i = 0; i < s.length(); i++) {
char c = s[i];
int cur = sz++;
st[cur].length = i + 1;
st[cur].firstPos = i;
int p = last;
for (; p != -1 && st[p].next[c] == -1; p = st[p].suffLink) {
st[p].next[c] = cur;
}
if (p == -1) {
st[cur].suffLink = 0;
} else {
int q = st[p].next[c];
if (st[p].length + 1 == st[q].length) {
st[cur].suffLink = q;
} else {
int clone = sz++;
st[clone].length = st[p].length + 1;
st[clone].next = st[q].next;
st[clone].suffLink = st[q].suffLink;
for (; p != -1 && st[p].next[c] == q; p = st[p].suffLink) {
st[p].next[c] = clone;
}
st[q].suffLink = clone;
st[cur].suffLink = clone;
}
}
last = cur;
}
for (int i = 1; i < sz; i++) {
st[st[i].suffLink].inv_sufflinks.push_back(i);
}
}
// usage example
int main() {
build_suffix_automaton("ababcc");
}