-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAC.cpp
More file actions
125 lines (125 loc) · 3.07 KB
/
AC.cpp
File metadata and controls
125 lines (125 loc) · 3.07 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
125
// Aho-Corasick automaton
// cses 2102
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
const int mod = 1e9 + 7;
int ans[MAXN];
struct AC
{
struct state
{
int nxt[26];
int fail;
vector<int>cnt;
}node[500005];
int sz;
void init() {
for (int i = 0 ; i < 500000 ; i++) {
memset(node[i].nxt, 0, sizeof(node[i].nxt));
node[i].fail = 0;
}
sz = 1;
}
void insert(string s, int num) {
int n = s.size();
int now = 0;
for (int i = 0 ; i < n ; i++) {
char c = s[i];
if (!node[now].nxt[c - 'a']) {
node[now].nxt[c - 'a'] = sz++;
}
now = node[now].nxt[c - 'a'];
}
node[now].cnt.push_back(num);
}
void build() {
node[0].fail = -1;
queue<int>q;
q.push(0);
while (q.size()) {
auto now = q.front();
q.pop();
for (int i = 0 ; i < 26 ; i++) {
if (node[now].nxt[i]) {
if (now == 0) {
node[node[now].nxt[i]].fail = 0;
}
else {
int v = node[now].fail;
while (v != -1) {
if (node[v].nxt[i]) {
node[node[now].nxt[i]].fail = node[v].nxt[i];
break;
}
v = node[v].fail;
}
if (v == -1) {
node[node[now].nxt[i]].fail = 0;
}
}
q.push(node[now].nxt[i]);
}
}
}
}
void match(string s) {
int now = 0;
for (int i = 0 ; i < s.size() ; i++) {
int c = s[i] - 'a';
if (node[now].nxt[c]) {
now = node[now].nxt[c];
}
else {
int p = node[now].fail;
while (p != -1 && node[p].nxt[c] == 0) {
p = node[p].fail;
}
if (p == -1) {
now = 0;
}
else {
now = node[p].nxt[c];
}
}
int a = now;
while (a) {
if (node[a].cnt.size() && ans[node[a].cnt[0]]) break;
for (auto &i : node[a].cnt)
ans[i] = 1;
a = node[a].fail;
}
}
}
}ac;
void solve() {
string str;
cin >> str;
int n;
cin >> n;
ac.init();
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
ac.insert(s, i);
}
ac.build();
ac.match(str);
for (int i = 1; i <= n; i++) {
if (ans[i]) {
cout << "YES\n";
}
else {
cout << "NO\n";
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
}