-
Notifications
You must be signed in to change notification settings - Fork 3
/
SuffixAutomaton.h
72 lines (66 loc) · 1.09 KB
/
SuffixAutomaton.h
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
struct Automaton {
struct Node {
int len;
Node *link;
vector<Node*> to;
Node(int _len = 0): len(_len) {
len = 0;
to.resize(26, NULL);
link = NULL;
}
Node* go(char c) {
c -= 'a';
return to[c];
}
};
Node *root, *last;
Automaton() {
root = last = new Node();
}
void add(char c) {
c -= 'a';
Node *cur = new Node(last->len + 1);
Node *tmp = last;
while (tmp) {
if (tmp->to[c]) {
break;
}
tmp->to[c] = cur;
tmp = tmp->link;
}
if (tmp) {
Node *nx = tmp->to[c];
if (nx->len == tmp->len + 1) {
cur->link = nx;
} else {
Node *clone = new Node(tmp->len + 1);
clone->to = nx->to;
clone->link = nx->link;
cur->link = clone;
nx->link = clone;
tmp->to[c] = clone;
while (tmp = tmp->link) {
if (tmp->to[c] == nx) {
tmp->to[c] = clone;
} else {
break;
}
}
}
} else {
cur->link = root;
}
last = cur;
}
Node* go(const string& s) const {
Node *result = root;
for (char c : s) {
if (!result) {
break;
} else {
result = result->go(c);
}
}
return result;
}
};