-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaho_corasick_automation.cpp
83 lines (72 loc) · 1.35 KB
/
aho_corasick_automation.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
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN = 1e6+7;
char c[MAXN];
struct Aho_corasick_automation {
int cnt = 0;
int val[MAXN] = {0};
int e[MAXN][27] = {0};
int fail[MAXN] = {0};
void ins(char *s){
int l = strlen(s);
int x = 0, y;
for(int i=0; i<l; i++){
y = s[i] - 'a';
if(!e[x][y]) e[x][y] = ++cnt;
x = e[x][y];
}
val[x] += 1;
}
void get_fail(){
queue<int> q;
int x = 0, y;
for(int i=0; i<26; i++){
if(e[x][i]){
fail[e[x][i]] = x;
q.push(e[x][i]);
}
}
while(!q.empty()){
// cout << "HI ";
int x = q.front();
q.pop();
for(int i=0; i<26; i++){
if(e[x][i]){
fail[e[x][i]] = e[fail[x]][i];
q.push(e[x][i]);
}else{
e[x][i] = e[fail[x]][i];
}
}
}
}
int ac_query(char *s){
int x = 0, y;
int l = strlen(s);
int ans = 0;
for(int i=0; i<l; i++){
y = s[i] - 'a';
x = e[x][y];
for(int t = x; t && val[t] != -1; t = fail[t]){
ans += val[t];
val[t] = -1;
}
}
return ans;
}
}AC;
int main(){
int n;
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%s", c);
AC.ins(c);
}
AC.get_fail();
scanf("%s", c);
printf("%d", AC.ac_query(c));
return 0;
}