Skip to content

Commit cea146e

Browse files
committed
回文树/回文自动机
1 parent 6d169c4 commit cea146e

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Palindromic-Tree.cpp

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// Problem Name: Palindromes
2+
// Source: [APIO2014]
3+
4+
#include <cstdio>
5+
#include <cstring>
6+
7+
#define NIL 0
8+
#define ALPHABET_SIZE 26
9+
#define STRING_LENGTH 100000
10+
11+
using namespace std;
12+
13+
struct node
14+
{
15+
node *next[ALPHABET_SIZE], *fail;
16+
int start, len;
17+
node (int _start = 0, int _len = 0) : fail(NIL), start(_start), len(_len) { memset(next, 0, sizeof(next)); }
18+
}*root, *empty, *last;
19+
20+
char str[STRING_LENGTH];
21+
int len;
22+
23+
void extend(char x, int pos)
24+
{
25+
node *u = last;
26+
while (str[pos] != str[pos - u->len - 1]) u = u->fail;
27+
if (u->next[x] == NIL)
28+
{
29+
node *cur = new node(pos - u->len - 1, u->len + 2);
30+
u->next[x] = cur;
31+
u = u->fail;
32+
if (u == NIL) cur->fail = empty;
33+
else
34+
{
35+
while (str[pos] != str[pos - u->len - 1]) u = u->fail;
36+
cur->fail = u->next[x];
37+
}
38+
last = cur;
39+
}
40+
else last = u->next[x];
41+
}
42+
43+
void build()
44+
{
45+
str[0] = '\xFF';
46+
root = new node(0, -1);
47+
empty = new node(0, 0);
48+
empty->fail = root;
49+
last = empty;
50+
for (int i = 1; i <= len; i++)
51+
{
52+
extend(str[i] - 'a', i);
53+
}
54+
}
55+
56+
void print_substring(int l, int r)
57+
{
58+
printf("\t");
59+
for (int i = l; i <= r; i++)
60+
{
61+
printf("%c", str[i]);
62+
}
63+
printf("\n");
64+
}
65+
66+
void dfs(node *u)
67+
{
68+
if (u->len > 0) print_substring(u->start, u->start + u->len - 1);
69+
for (int i = 0; i < ALPHABET_SIZE; i++)
70+
{
71+
if (u->next[i] != NIL) dfs(u->next[i]);
72+
}
73+
}
74+
75+
int main()
76+
{
77+
scanf("%s", str + 1);
78+
len = strlen(str + 1);
79+
build();
80+
printf("odd:\n");
81+
dfs(root);
82+
printf("even:\n");
83+
dfs(empty);
84+
return 0;
85+
}

0 commit comments

Comments
 (0)