-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathternary_search_tree.cpp
79 lines (71 loc) · 1.3 KB
/
ternary_search_tree.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
#include <cstdio>
#include <deque>
#include <queue>
#include <stack>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <bitset>
#include <list>
#include <set>
#include <map>
using namespace std;
struct Node {
char c;
Node *l, *r, *eq;
bool is_end;
Node(char ch = '0') : l(NULL), r(NULL), eq(NULL), c(ch), is_end(false) {}
};
typedef Node* pnode;
inline void add(pnode &root, const char *s) {
if (root == NULL) {
root = new Node(s[0]);
}
if (root->c < s[0]) {
add(root->l, s);
} else if (root->c > s[0]) {
add(root->r, s);
} else {
if (s[0] == 0) {
root->is_end = true;
} else {
add(root->eq, s + 1);
}
}
}
inline bool check(pnode &root, const char *s) {
if (root == NULL) {
return false;
}
if (root->c < s[0]) {
return check(root->l, s);
}
if (root->c > s[0]) {
return check(root->r, s);
}
if (s[0] == 0) {
return root->is_end;
}
return check(root->eq, s + 1);
}
int main() {
int q;
scanf("%d", &q);
pnode root = NULL;
while (q--) {
int cmd;
string z;
cin >> cmd >> z;
if (cmd == 1) { // add
add(root, z.c_str());
} else { // check
if (check(root, z.c_str())) {
puts("YES");
} else {
puts("NO");
}
}
}
}