-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathFinding Patterns.cpp
73 lines (64 loc) · 1.53 KB
/
Finding Patterns.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
#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5+5;
struct Node {
int len, link, cnt, firstpos;
map<char,int> nxt;
} node[2*maxN];
char S[maxN], T[5*maxN];
int N, M, K, sz, last;
void extend(char c){
int cur = sz++;
node[cur].len = node[last].len + 1;
int p = last;
while(p != -1 && !node[p].nxt.count(c)){
node[p].nxt[c] = cur;
p = node[p].link;
}
if(p == -1){
node[cur].link = 0;
} else {
int q = node[p].nxt[c];
if(node[p].len + 1 == node[q].len){
node[cur].link = q;
} else {
int clone = sz++;
node[clone].len = node[p].len + 1;
node[clone].nxt = node[q].nxt;
node[clone].link = node[q].link;
while(p != -1 && node[p].nxt[c] == q){
node[p].nxt[c] = clone;
p = node[p].link;
}
node[q].link = node[cur].link = clone;
}
}
last = cur;
}
void init(){
node[0].len = 0;
node[0].link = -1;
sz = 1;
last = 0;
}
bool query(){
int u = 0;
for(int i = 0; i < M; i++){
char c = T[i];
if(!node[u].nxt.count(c)) return false;
else u = node[u].nxt[c];
}
return true;
}
int main(){
scanf(" %s %d", S, &K);
N = (int) strlen(S);
init();
for(int i = 0; i < N; i++)
extend(S[i]);
for(int i = 0; i < K; i++){
scanf(" %s", T);
M = (int) strlen(T);
printf("%s\n", query() ? "YES" : "NO");
}
}