-
Notifications
You must be signed in to change notification settings - Fork 0
/
aho-corasick_automaton.cpp
54 lines (51 loc) · 1.22 KB
/
aho-corasick_automaton.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
struct ac_automaton
{
int ch[maxn][26], val[maxn];
int f[maxn], last[maxn], sz;
void init()
{
sz = 1; memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val)); memset(f, 0, sizeof(f));
memset(last, 0, sizeof(last));
}
void insert(char * s, int v)
{
int u = 0;
for(int i = 0; s[i]; ++i)
{
int c = tran[s[i]];
if(!ch[u][c])
{
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = v;
}
void getfail()
{
queue<int> q; f[0] = 0;
for(int c = 0; c < 26; ++c)
{
int u = ch[0][c];
if(u) { f[u] = 0; q.push(u); last[u] = 0; }
else ch[0][c] = 0;
}
while(!q.empty())
{
int r = q.front(); q.pop();
for(int c = 0; c < 26; ++c)
{
int u = ch[r][c];
if(u)
{
q.push(u);
f[u] = ch[f[r]][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
else ch[r][c] = ch[f[r]][c];
}
}
}
}a;