-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAC_auto.cpp
executable file
·113 lines (101 loc) · 2.56 KB
/
AC_auto.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
/*
*@author:cmershen
*@description:Trie图模板,输入一组字符串(和谐词汇)和一个长字符串(代表文章),判断文章里是否有和谐词汇
*/
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int max_sigma = 26;
class Node{
public:
Node* fail;
Node* next[max_sigma];
int cnt;
Node(){
memset(next, 0, sizeof(next));
fail = NULL;
cnt = 0;
}
};
class AC_automato : public Node{
public:
Node *root;
int head, tail;
void clear(){
root = new Node();
head = tail = 0;
}
void insert(char* s){
int c;
Node* p = root;
while(*s != NULL){
c = *s - 'a';
if(p->next[c] == NULL) p->next[c] = new Node();
p = p->next[c];
s ++;
}
p->cnt ++;
}
void build(){
root->fail = NULL;
queue<Node* > q;
q.push(root);
while(!q.empty()){
Node* tmp = q.front();
Node* p = NULL;
q.pop();
for(int i=0; i<max_sigma; i++){
if(tmp->next[i] != NULL){
if(tmp == root) tmp->next[i]->fail = root;
else{
p = tmp->fail;
while(p != NULL){
if(p->next[i] != NULL){
tmp->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if(p == NULL) tmp->next[i]->fail = root;
}
q.push(tmp->next[i]);
}
}
}
}
int find(char* s){
int cnt = 0, c;
Node* p = root;
while(*s != NULL){
c = *s - 'a';
while(p->next[c] == NULL && p != root)
p = p->fail;
p = p->next[c];
if(p == NULL) p = root;
Node* tmp = p;
while(tmp != root && tmp->cnt != -1){
cnt += tmp->cnt;
tmp->cnt = -1;
tmp = tmp->fail;
}
s ++;
}
return cnt;
}
} ac;
char word[1000002]; //word开小了,会RE!!!
int main(){
int n;
while(scanf("%d", &n) == 1){
ac.clear();
for(int i=0; i<n; i++){
scanf("%s", word);
ac.insert(word);
}
ac.build();
scanf("%s", word);
puts(ac.find(word) ? "YES" : "NO");
}
return 0;
}