-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtrie.cpp
More file actions
41 lines (36 loc) · 780 Bytes
/
trie.cpp
File metadata and controls
41 lines (36 loc) · 780 Bytes
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
#include <bits/stdc++.h>
using namespace std;
const int ALPHA = 26, off = 'a';
struct Node {
array<Node*, ALPHA> nxt;
int terminal = 0;
Node() { nxt.fill(NULL); }
};
struct Trie {
Node* root;
Trie(){ root = new Node(); }
void add(string &s){
Node* t = root;
for(auto c : s){ c -= off;
if(!t->nxt[c])
t->nxt[c] = new Node();
t = t->nxt[c];
}
t->terminal++;
}
int count(string &s){
Node* t = root;
for(auto c : s){ c -= off;
if(!t->nxt[c]) return 0;
t = t->nxt[c];
}
return t->terminal;
}
};
/*LATEX_DESC_BEGIN***************************
**Trie - Arvore de Prefixos**
insert(P) - O(|P|)
count(P) - O(|P|)
sigma - Tamanho do alfabeto
off - primeiro simbolo do alfabeto (offset)
*****************************LATEX_DESC_END*/