-
Notifications
You must be signed in to change notification settings - Fork 6
/
Simple Trie.cpp
88 lines (79 loc) · 1.74 KB
/
Simple 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <bits/stdc++.h>
using namespace std;
#define Long long long
#define ld long double
#define pii pair<int, int>
#define pli pair<Long, int>
const int me = 100025;
const int mod = 1.e9 + 7;
class Trie{
private:
const static int ALPHABET = 26;
const static char FIRST_LETTER = 'a';
struct node{
int link[ALPHABET];
bool is_word;
node(){
for(int i = 0; i < ALPHABET; i ++)
link[i] = -1;
is_word = false;
}
};
node make_node(){
node c = node();
return c;
}
int get(char x){
return x - FIRST_LETTER;
}
void traverse(int pos, string s){
if(trie[pos].is_word){
cout << "word: " << s << endl;
}
for(int i = 0; i < ALPHABET; i ++)
if(trie[pos].link[i] != -1)
traverse(trie[pos].link[i], s + (char)(i + 'a'));
}
public:
vector<node> trie;
int Size;
Trie(){
trie.push_back(make_node());
Size = 1;
}
~Trie() {
};
int size(){
return Size;
}
void add(string s){
int pos = 0;
for(char i : s){
int x = get(i);
if(trie[pos].link[x] == -1){
node c = make_node();
trie.push_back(c);
trie[pos].link[x] = Size;
pos = Size ++;
}
else{
pos = trie[pos].link[x];
}
}
trie[pos].is_word = true;
}
void output(){
traverse(0, "");
}
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
Trie t = Trie();
t.add("abcd");
t.add("bdefd");
t.add("aaa");
t.add("abcc");
t.output();
return 0;
}