-
Notifications
You must be signed in to change notification settings - Fork 438
/
Suffix-Automaton.cpp
71 lines (64 loc) · 964 Bytes
/
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
#include <cstdio>
#include <cstring>
#define NIL 0
#define ALPHABET_SIZE 26
using namespace std;
struct node
{
node *next[ALPHABET_SIZE], *parent;
int len;
node(int _len = 0) : len(_len) { memset(next, 0, sizeof(next)), parent = NIL; }
}*root, *last;
char s[100000];
int len;
void init()
{
root = new node(0);
last = root;
}
void extend(int x)
{
node *p = last;
node *np = new node(p->len + 1);
while (p != NIL && p->next[x] == NIL)
{
p->next[x] = np;
p = p->parent;
}
if (p == NIL)
{
np->parent = root;
}
else
{
node *q = p->next[x];
if (q->len == p->len + 1)
{
np->parent = q;
}
else
{
node *nq = new node;
*nq = *q;
nq->len = p->len + 1;
q->parent = np->parent = nq;
while (p != NIL && p->next[x] == q)
{
p->next[x] = nq;
p = p->parent;
}
}
}
last = np;
}
int main()
{
scanf("%s", s);
len = strlen(s);
init();
for (int i = 0; i < len; i++)
{
extend(s[i] - 'a');
}
return 0;
}