-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_trie.hpp
More file actions
40 lines (40 loc) · 904 Bytes
/
binary_trie.hpp
File metadata and controls
40 lines (40 loc) · 904 Bytes
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
#pragma once
//! @code
//! binary_trie bt;
//! bt.update(num, 1); // insert
//! bt.update(num, -1); // erase
//! @endcode
//! @time O(q * mx_bit)
//! @space O(q * mx_bit)
const ll mx_bit = 1LL << 60;
struct binary_trie {
struct node {
int siz = 0;
array<int, 2> next = {-1, -1};
};
deque<node> t;
binary_trie(): t(1) {}
void update(ll num, int delta) {
int v = 0;
for (ll bit = mx_bit; bit; bit /= 2) {
bool b = num & bit;
if (t[v].next[b] == -1) {
t[v].next[b] = sz(t);
t.emplace_back();
}
v = t[v].next[b];
t[v].siz += delta;
}
}
ll walk(ll num) {
int v = 0;
ll res = 0;
for (ll bit = mx_bit; bit; bit /= 2) {
bool b = num & bit;
int u = t[v].next[b];
if (u != -1 && t[u].siz > 0) v = u, res |= num & bit;
else v = t[v].next[!b], res |= (~num) & bit;
}
return res;
}
};