-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAho Corasick.cpp
156 lines (142 loc) · 2.98 KB
/
Aho Corasick.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define sc second
using namespace std;
struct State
{
State* suffixLink=NULL;
State* parent=NULL;
char parentChar='\0';
map<char,State*> children;
vector<int> wordIds;
};
void trieFonk(State *state, string s, int wId)
{
for(char ch:s)
{
if(state->children[ch]!=0)
{
state=state->children[ch];
}
else
{
State *t =new State;
state->children[ch]=t;
t->parent=state;
state=t;
state->parentChar=ch;
}
}
state->wordIds.pb(wId);
}
State *root;
void bfs(State *state)
{
if(state==root)
{
state->suffixLink=root;
return;
}
if(state->parent==root)
{
state->suffixLink=root;
return;
}
State *currentBest = state->parent->suffixLink;
if(currentBest->children[state->parentChar]!=NULL)
{
state->suffixLink = currentBest->children[state->parentChar];
}
while(true)
{
if(currentBest->children[state->parentChar]!=NULL)
{
state->suffixLink = currentBest->children[state->parentChar];
break;
}
if(currentBest==root)
{
state->suffixLink = root;
break;
}
currentBest = currentBest->suffixLink;
}
}
void prepare()
{
queue<State*> state_q;
state_q.push(root);
while(!state_q.empty())
{
State *current = state_q.front();
state_q.pop();
bfs(current);
for(auto x:current->children)
{
if(x.sc!=NULL) state_q.push(x.sc);
}
}
}
void deleteStates()
{
queue<State*> state_q;
state_q.push(root);
while(!state_q.empty())
{
State *current = state_q.front();
state_q.pop();
for(auto x:current->children)
{
if(x.sc!=NULL) state_q.push(x.sc);
}
delete current;
}
}
int main(int argc, char const *argv[])
{
string text;//text that patterns search in
cin>>text;
text+='$';
root = new State;
int q;
cin>>q;
vector<string> queries;// patterns
vector<bool> results(q,0);// pattern found or not
for(int i=0;i<q;i++)
{
string s;
cin>>s;
queries.pb(s);
trieFonk(root, s, i);
}
prepare();
State *state=root;
for(auto s:text)
{
while(true)
{
if(!state->wordIds.empty())
{
for(auto x:state->wordIds)
{
results[x]=1;
}
}
if(state->children[s]!=0)
{
state=state->children[s];
break;
}
if(state==root) break;
state=state->suffixLink;
}
}
for(auto x:results)//if a pattern found print 'y' else 'n'
{
if(x) cout<<"y\n";
else cout<<"n\n";
}
deleteStates();
return 0;
}