-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathaho.cpp
executable file
·43 lines (43 loc) · 983 Bytes
/
aho.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
// Aho-Corasick
// https://youtu.be/BYoRvdgI5EU?t=9633
struct Aho {
using MP = unordered_map<char,int>;
vector<MP> to;
vector<int> cnt, fail;
Aho(): to(1), cnt(1) {}
int add(const string& s) {
int v = 0;
for (char c : s) {
if (!to[v].count(c)) {
to[v][c] = to.size();
to.push_back(MP());
cnt.push_back(0);
}
v = to[v][c];
}
cnt[v]++;
return v;
}
void init() {
fail = vector<int>(to.size(), -1);
queue<int> q;
q.push(0);
while (!q.empty()) {
int v = q.front(); q.pop();
for (auto [c,u] : to[v]) {
fail[u] = (*this)(fail[v],c);
cnt[u] += cnt[fail[u]];
q.push(u);
}
}
}
int operator()(int v, char c) const {
while (v != -1) {
auto it = to[v].find(c);
if (it != to[v].end()) return it->second;
v = fail[v];
}
return 0;
}
int operator[](int v) const { return cnt[v];}
};