-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathPersistent Trie.cpp
78 lines (69 loc) · 1.45 KB
/
Persistent 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
#include <bits/stdc++.h>
using namespace std;
// Problem: find maximum value (x^a[j]) in the range (l,r) where l<=j<=r
const int N = 1e5 + 100;
const int K = 15;
struct node_t;
typedef node_t * pnode;
struct node_t {
int time;
pnode to[2];
node_t() : time(0) {
to[0] = to[1] = 0;
}
bool go(int l) const {
if (!this) return false;
return time >= l;
}
pnode clone() {
pnode cur = new node_t();
if (this) {
cur->time = time;
cur->to[0] = to[0];
cur->to[1] = to[1];
}
return cur;
}
};
pnode last;
pnode version[N];
void insert(int a, int time) {
pnode v = version[time] = last = last->clone();
for (int i = K - 1; i >= 0; --i) {
int bit = (a >> i) & 1;
pnode &child = v->to[bit];
child = child->clone();
v = child;
v->time = time;
}
}
int query(pnode v, int x, int l) {
int ans = 0;
for (int i = K - 1; i >= 0; --i) {
int bit = (x >> i) & 1;
if (v->to[bit]->go(l)) { // checking if this bit was inserted before the range
ans |= 1 << i;
v = v->to[bit];
} else {
v = v->to[bit ^ 1];
}
}
return ans;
}
void solve() {
int n, q;
scanf("%d %d", &n, &q);
last = 0;
for (int i = 0; i < n; ++i) {
int a;
scanf("%d", &a);
insert(a, i);
}
while (q--) {
int x, l, r;
scanf("%d %d %d", &x, &l, &r);
--l, --r;
printf("%d\n", query(version[r], ~x, l));
// Trie version[r] contains the trie for [0...r] elements
}
}