forked from bicsi/code_snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaho_corasick.cpp
More file actions
58 lines (44 loc) · 1.17 KB
/
Copy pathaho_corasick.cpp
File metadata and controls
58 lines (44 loc) · 1.17 KB
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
struct AhoCorasick {
struct Node {
int link;
map<char, int> leg;
};
vector<Node> T;
int root = 0, nodes = 1;
AhoCorasick(int sz) : T(sz) {}
// Adds a word to trie and returns the end node
int AddWord(const string &word) {
int node = root;
for(auto c : word) {
auto &nxt = T[node].leg[c];
if(nxt == 0)
nxt = nodes++;
node = nxt;
}
return node;
}
// Advances from a node with a character (like an automaton)
int Advance(int node, char chr) {
while(node != -1 && T[node].leg.count(chr) == 0)
node = T[node].link;
if(node == -1)
return root;
return T[node].leg[chr];
}
// Builds links
void BuildLinks() {
queue<int> Q;
Q.push(root);
T[root].link = -1;
while(!Q.empty()) {
int node = Q.front();
Q.pop();
for(auto &p : T[node].leg) {
int vec = p.second;
char chr = p.first;
T[vec].link = Advance(T[node].link, chr);
Q.push(vec);
}
}
}
};