-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
100 lines (74 loc) · 1.87 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
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
89
90
91
92
93
94
95
96
97
98
99
100
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
struct Node {
int idx[26];
bool finish;
};
struct Trie {
vector<Node> nodes{Node()};
void insert(const string s) {
int cur = 0;
for (char c : s) {
if (!nodes[cur].idx[c - 97]) {
nodes[cur].idx[c - 97] = nodes.size();
nodes.push_back(Node());
}
cur = nodes[cur].idx[c - 97];
}
nodes[cur].finish = true;
}
bool search(const string s) {
int cur = 0;
for (char c : s) {
if (!nodes[cur].idx[c - 97])
return false;
cur = nodes[cur].idx[c - 97];
}
return nodes[cur].finish;
}
};
//--------------------------------------------------------------------------------
struct Trie {
map<char, Trie *> nxt;
bool finish;
Trie() { finish = false; }
~Trie() { nxt.clear(); }
bool insert(const char *s) {
if (*s == '\0') {
finish = true;
return !nxt.sz;
}
if (finish)
return false;
if (nxt.find(*s) == nxt.end())
nxt[*s] = new Trie;
return nxt[*s]->insert(s + 1);
}
};
//--------------------------------------------------------------------------------
struct Trie {
vector<pair<char, Trie *>> nxt;
bool finish;
Trie() { finish = false; }
~Trie() { nxt.clear(); }
void insert(const char *s) {
if (*s == '\0') {
finish = true;
return;
}
for (auto node : nxt) {
if (node.fi == *s) {
node.se->insert(s + 1);
return;
}
}
nxt.push_back({*s, new Trie});
nxt.bk.se->insert(s + 1);
}
};