-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathAho-Corasick.cpp
56 lines (49 loc) · 1.07 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
const int N = ; // total number of nodes in the dict tree
const int CD = ; // alphabet number
//template based
int sz, ch[N][CD], val[N], fail[N], Q[N], ID[512];
//problem needed
void Init() {
fail[0] = 0;
for (int i = 0; i < 26; i++) {
ID[i + 'a'] = i;
}
}
void Reset() {
memset (ch[0], 0, sizeof(ch));
sz = 1;
}
void Insert(char *a) {
int p = 0;
for(; *a; a++) {
int c = ID[*a];
if (!ch[p][c]) {
memset (ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[p][c] = sz++;
}
p = ch[p][c];
}
val[p] = 1;
}
void Construct() {
int *s = Q, *e = Q;
for (int i = 0; i < CD; i++) {
if (ch[0][i]) {
fail[ ch[0][i] ] = 0;
*e ++ = ch[0][i];
}
}
while (s != e) {
int u = *s++;
for (int i = 0; i < CD ;i++){
int &v = ch[u][i];
if(v) {
*e++ = v;
fail[v] = ch[ fail[u] ][i];
} else {
v = ch[ fail[u] ][i];
}
}
}
}