-
Notifications
You must be signed in to change notification settings - Fork 7
/
mytrie.cpp
48 lines (41 loc) · 997 Bytes
/
mytrie.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
class TRIE {
private:
typedef struct node {
node *bit[2];
int cnt = 0;
} * nodeptr;
nodeptr root;
public:
TRIE() { root = new node(); }
void insert(int val) {
nodeptr curr = root;
for (int i = 30; i >= 0; i--) {
int currBit = (val >> i) & 1LL;
if (curr->bit[currBit] == NULL)
curr->bit[currBit] = new node();
curr = curr->bit[currBit];
curr->cnt++;
}
}
void remove(int val) {
nodeptr curr = root;
for (int i = 30; i >= 0; i--) {
int currBit = (val >> i) & 1LL;
curr = curr->bit[currBit];
curr->cnt--;
}
}
int query(int val) { // max xor with val query
int ans = 0;
nodeptr curr = root;
for (int i = 30; i >= 0; i--) {
int currBit = (val >> i) & 1LL;
if (curr->bit[currBit ^ 1] != NULL && curr->bit[currBit ^ 1]->cnt > 0) {
ans += (1LL << i);
curr = curr->bit[currBit ^ 1];
} else
curr = curr->bit[currBit];
}
return ans;
}
};