-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhdu_2222_Keywords Search_1.cpp
129 lines (120 loc) · 2.5 KB
/
hdu_2222_Keywords Search_1.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
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
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <climits>
#include <numeric>
using namespace std;
const int CHARSET = 26;
//const int MAX_N_NODES = 500005;
const int MAX_N_NODES = 250005;
const int L = 1000005;
const int N = 10001;
int pointer, n;
char s[L];
struct Node {
Node *ch[CHARSET], *fail;
int value; bool flag;
Node() {
memset(ch, 0, sizeof ch);
fail = 0;
value = 0;
flag = false;
}
Node*go(int w);
}*root;
Node nodePool[MAX_N_NODES], *cur;
Node *que[MAX_N_NODES];
Node* newNode() {
Node*t = cur++;
memset(t->ch, 0, sizeof t->ch);
t->fail = 0;
t->flag = false;
t->value = 0;
return t;
}
Node* Node::go(int w) {
if (ch[w] == 0) {
ch[w] = newNode();
}
return ch[w];
}
void init() {
cur = nodePool;
root = newNode();
}
void build() {
int qh = 0, qt = 0;
que[qt++] = root;
while (qh < qt) {
Node*t = que[qh++];
for (int c = 0; c < CHARSET; ++c) {
Node*v = t->ch[c];
if (!v)
continue;
Node*f = t->fail;
while (f && f->ch[c] == 0)
f = f->fail;
if (f == 0)
v->fail = root;
else
v->fail = f->ch[c];
que[qt++] = v;
}
}
}
void insert(char *str,int value)
{
int i, j, l = strlen(str);
Node *node = root;
for(i = 0; i < l; i ++)
node = node->go(str[i] - 'a');
node->value += 1;
}
int AC(char* str)
{
int i, j, l = strlen(str), res = 0, state = 0;
Node *node = root, *tNode, *fNode;
for(i = 0; i < l; i ++)
{
tNode = node->ch[ str[i] - 'a' ];
if(!tNode)
{
fNode = node->fail;
while(fNode && fNode->ch[str[i] -'a'] == 0)
fNode = fNode->fail;
if(!fNode)
tNode = root;
else
tNode = fNode->ch[ str[i] - 'a' ];
}
node = tNode;
while(tNode)
{
if(tNode->flag == false)
res += tNode->value, tNode->flag = true;
tNode = tNode->fail;
}
}
return res;
}
int main()
{
int T,i,j,ans;
scanf("%d",&T);
while(T--)
{
init();
scanf("%d",&n);
for(i = 1; i <= n; i ++)
{
scanf("%s",s);
insert(s, i);
}
build();
scanf("%s",s);
ans = AC(s);
printf("%d\n",ans);
}
return 0;
}