Skip to content

Commit ec3a135

Browse files
committed
后缀自动机(未验证正确性)
1 parent 847ca7a commit ec3a135

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Suffix-Automaton.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <cstdio>
2+
#include <cstring>
3+
4+
#define NIL 0
5+
#define ALPHABET_SIZE 26
6+
7+
using namespace std;
8+
9+
struct node
10+
{
11+
node *next[ALPHABET_SIZE], *parent;
12+
int len;
13+
node(int _len = 0) : len(_len) { memset(next, 0, sizeof(next)), parent = NIL; }
14+
}*root, *last;
15+
16+
char s[100000];
17+
int len;
18+
19+
void init()
20+
{
21+
root = new node(0);
22+
last = root;
23+
}
24+
25+
void extend(int x)
26+
{
27+
node *p = last;
28+
node *np = new node(p->len + 1);
29+
while (p != NIL && p->next[x] == NIL)
30+
{
31+
p->next[x] = np;
32+
p = p->parent;
33+
}
34+
if (p == NIL)
35+
{
36+
np->parent = root;
37+
}
38+
else
39+
{
40+
node *q = p->next[x];
41+
if (q->len == p->len + 1)
42+
{
43+
np->parent = q;
44+
}
45+
else
46+
{
47+
node *nq = new node;
48+
*nq = *q;
49+
nq->len = p->len + 1;
50+
q->parent = np->parent = nq;
51+
while (p != NIL && p->next[x] == q)
52+
{
53+
p->next[x] = nq;
54+
p = p->parent;
55+
}
56+
}
57+
}
58+
last = np;
59+
}
60+
61+
int main()
62+
{
63+
scanf("%s", s);
64+
len = strlen(s);
65+
init();
66+
for (int i = 0; i < len; i++)
67+
{
68+
extend(s[i] - 'a');
69+
}
70+
return 0;
71+
}

0 commit comments

Comments
 (0)