-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie_Bits.cpp
More file actions
117 lines (104 loc) · 2.37 KB
/
Trie_Bits.cpp
File metadata and controls
117 lines (104 loc) · 2.37 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <bits/stdc++.h>
using namespace std;
// Tire on Bits, O(n)
template <typename T>
struct Trie {
int sz;
vector<int> cnt_prefix, cnt_word;
vector<array<int, 2>> nxt;
const int B = numeric_limits<T>::digits - 1;
Trie(int n) : sz(1) {
cnt_prefix.assign(n, 0);
cnt_word.assign(n, 0);
nxt.assign(n, array<int, 2>());
}
void insert(const T &x) {
int v = 0;
for (int i = B; i >= 0; i--) {
int bit = x >> i & 1;
if (!nxt[v][bit]) {
nxt[v][bit] = sz++;
}
v = nxt[v][bit];
cnt_prefix[v]++;
}
cnt_word[v]++;
}
void erase(const T &x) {
int v = 0;
for (int i = B; i >= 0; i--) {
int bit = x >> i & 1;
v = nxt[v][bit];
cnt_prefix[v]--;
assert(cnt_prefix[v] >= 0);
}
cnt_word[v]--;
assert(cnt_word[v] >= 0);
}
int count_prefix(const T &x) {
int v = 0;
for (int i = B; i >= 0; i--) {
int bit = x >> i & 1;
if (!nxt[v][bit]) {
return 0;
}
v = nxt[v][bit];
}
return cnt_prefix[v];
}
int count_word(const T &x) {
int v = 0;
for (int i = B; i >= 0; i--) {
int bit = x >> i & 1;
if (!nxt[v][bit]) {
return 0;
}
v = nxt[v][bit];
}
return cnt_word[v];
}
T max_xor(const T &x) {
T res{};
int v = 0;
for (int i = B; i >= 0; i--) {
int bit = x >> i & 1;
if (cnt_prefix[nxt[v][bit ^ 1]]) {
v = nxt[v][bit ^ 1];
res += T(1) << i;
}
else {
v = nxt[v][bit];
}
}
return res;
}
};
void solve() {
int q;
cin >> q;
const int N = 1e6;
Trie<int> trie(N);
while (q--) {
int op, x;
cin >> op >> x;
if (op == 1) {
trie.insert(x);
}
else if (op == 2) {
trie.erase(x);
}
else if (op == 3) {
cout << trie.max_xor(x) << '\n';
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}