-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathaho Corasick.cpp
85 lines (74 loc) · 1.78 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
# include <bits/stdc++.h>
# define NR 1000005
# define L 10005
# define N 105
# define sigma 26
using namespace std;
ifstream f("ahocorasick.in");
ofstream g("ahocorasick.out");
struct trie {
int cnt; //nuamrul de aparitii
trie *fiu[sigma], *fail;
vector <trie*> adj;
trie () {
cnt=0; fail=NULL; adj.clear();
memset (fiu, 0, sizeof(fiu));
}
}*poz[N];
trie *T=new trie;
int i,j,n,m,l;
char s[NR], var[L];
trie *ins (trie *nod, char *s) {
if (*s=='\0') return nod;
if (nod->fiu[*s - 'a']==NULL)
nod->fiu[*s - 'a']=new trie;
return ins(nod->fiu[*s - 'a'], s+1);
}
void BFS () {
queue <trie*> q;
q.push(T);
while (! q.empty()) {
trie *nod=q.front(); q.pop();
for (int i=0; i<sigma; ++i) {
if (nod->fiu[i]!=NULL) {
trie *aux=nod->fail;
while (aux!=NULL && aux->fiu[i]==NULL)
aux=aux->fail;
if (aux==NULL) aux=T;
else aux=aux->fiu[i];
nod->fiu[i]->fail=aux;
aux->adj.push_back(nod->fiu[i]);
q.push(nod->fiu[i]);
}
}
}
}
void DFS (trie *nod) {
for (auto &x: nod->adj) {
DFS(x);
nod->cnt += x->cnt;
}
}
int main ()
{
f.getline (s+1, NR); l=strlen(s+1);
f>>n; f.get();
for (int i=1; i<=n; ++i) {
f.getline(var+1, L);
poz[i]=ins(T, var+1);
}
BFS ();
//facem ca la KMP
trie *curr=T;
for (int i=1; i<=l; ++i) {
while (curr!=NULL && curr->fiu[s[i]-'a']==NULL)
curr=curr->fail;
if (curr==NULL) curr=T;
else curr=curr->fiu[s[i]-'a'];
curr->cnt ++;
}
DFS(T);
for (int i=1; i<=n; ++i)
g<<poz[i]->cnt<<"\n";
return 0;
}