-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9250.cpp
More file actions
125 lines (93 loc) Β· 2.24 KB
/
9250.cpp
File metadata and controls
125 lines (93 loc) Β· 2.24 KB
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
// μνΈ-μ½λΌμ
#include <iostream>
#include <string>
#include <queue>
#include <stdio.h>
using namespace std;
struct TRIE
{
TRIE *node[26];
TRIE *fail;
bool finish;
TRIE(){
finish = false;
for(int i=0; i<26; i++)
node[i] = NULL;
}
void insert(const char *str){
if(!*str){
finish = true;
return;
}
int cur = *str - 'a';
if(!node[cur])
node[cur] = new TRIE();
node[cur]->insert(str + 1);
}
void init(){
queue<TRIE*> q;
q.push(this);
while(!q.empty()){
TRIE *now = q.front();
q.pop();
for(int i=0; i<26; i++){
TRIE *next = now->node[i];
if(!next)
continue;
if(now == this)
next->fail = this;
else{
TRIE *temp = now->fail;
while(temp!=this && temp->node[i]==NULL){
// cout<<this<<"\n";
temp = temp->fail;
}
if(temp->node[i])
temp = temp->node[i];
next->fail = temp;
}
if(next->fail->finish)
next->finish = true;
q.push(next);
}
}
}
bool query(string &str){
TRIE *cur = this;
for(int i=0; i<str.size(); i++){
int now = str[i] - 'a';
while(cur!=this && !(cur->node[now]))
cur = cur->fail;
if(cur->node[now]){
cur = cur->node[now];
}
if(cur->finish)
return true;
}
return false;
}
};
int main(void){
ios::sync_with_stdio(false);
cin.tie(0);
TRIE *Root = new TRIE();
int N;
cin>>N;
for(int i=0; i<N; i++){
string s;
cin>>s;
Root->insert(s.c_str());
}
Root->init();
int Q;
cin>>Q;
while(Q--){
string s;
cin>>s;
if(Root->query(s))
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}