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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<queue>
using namespace std;
const int maxnode = 500000+5;
struct trie
{
int sz, root, val[maxnode], next[maxnode][30], fail[maxnode];
int cnt = 0;
queue<int>q;
void init()
{
sz = root = 0;
val[0] = 0;
memset(next, -1, sizeof(next));
}
void insert(string s)
{
int i, j, u = 0, len = s.size();
for (i = 0; i < len; i++)
{
int c = s[i] - 'a';
if (next[u][c] == -1)
{
sz++;
val[sz] = 0;
next[u][c] = sz;
}
u = next[u][c];
}
val[u]++;
}
void build()
{
while (!q.empty())
{
q.pop();
}
for (int i = 0; i < 25; i++)
{
if (next[0][i] != -1)
{
fail[next[0][i]] = 0;
q.push(next[0][i]);
}
}
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = 0; i < 25; i++)
{
if (next[u][i] != -1)
{
q.push(next[u][i]);
int tmp = fail[u];
while (tmp&&next[tmp][i]==-1)
{
tmp = fail[tmp];
}
tmp = next[tmp][i];
if (tmp == -1)
{
tmp = 0;
}
fail[next[u][i]] = tmp;
}
}
}
}
void query(string s)
{
cnt = 0;
int len = s.size();
int u = 0;
for (int i = 0; i < len; i++)
{
int c = s[i] - 'a';
while (next[u][c] == -1)
{
u = fail[u];
if (u == 0)
{
if (next[u][c] != -1)
u = next[u][c];
}
if (u == 0)
{
goto end;
}
}
u = next[u][c];
int tmp = u;
while (tmp != 0)
{
if (val[tmp] >= 0)
{
cnt += val[tmp];
val[tmp] = -1;
}
else
{
break;
}
tmp = fail[tmp];
}
end:;
}
}
}ac;
int main()
{
string s[4];
s[0] = "abcd";
s[1] = "abd";
s[2] = "bce";
s[3] = "cd";
ac.init();
for (int i = 0; i < 4; i++)
{
ac.insert(s[i]);
}
ac.build();
string p = "abcde";
ac.query(p);
cout << ac.cnt;
}