-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTrie.cpp
61 lines (57 loc) · 1.3 KB
/
Trie.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
/*8<
@Tittle:Trie
@Description:
\begin{compactitem}
\item build with the size of the alphabet
$(sigma)$ and the first char $(norm)$ \item
$insert(s)$ insert the string in the trie
$O(|s|*sigma)$ \item $erase(s)$ remove the
string from the trie $O(|s|)$ \item
$find(s)$ return the last node from the
string s, 0 if not found $O(|s|)$
\end{compactitem}
>8*/
struct trie {
vi2d to;
vi end, pref;
int sigma;
char norm;
trie(int sigma_ = 26, char norm_ = 'a')
: sigma(sigma_), norm(norm_) {
to = {vector<int>(sigma)};
end = {0}, pref = {0};
}
int next(int node, char key) {
return to[node][key - norm];
}
void insert(const string &s) {
int x = 0;
for (auto c : s) {
int &nxt = to[x][c - norm];
if (!nxt) {
nxt = len(to);
to.push_back(vi(sigma));
end.emplace_back(0), pref.emplace_back(0);
}
x = nxt, pref[x]++;
}
end[x]++, pref[0]++;
}
void erase(const string &s) {
int x = 0;
for (char c : s) {
int &nxt = to[x][c - norm];
x = nxt, pref[x]--;
if (!pref[x]) nxt = 0;
}
end[x]--, pref[0]--;
}
int find(const string &s) {
int x = 0;
for (auto c : s) {
x = to[x][c - norm];
if (!x) return 0;
}
return x;
}
};