forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie - Maximum XOR Queries
130 lines (115 loc) · 2.33 KB
/
Trie - Maximum XOR Queries
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
118
119
120
121
122
123
124
125
126
127
128
129
#include<bits/stdc++.h>
using namespace std;
struct Node {
Node * children[2];
bool containsKey(int ind) {
return (children[ind] != NULL);
}
Node * get(int ind) {
return children[ind];
}
void put(int ind, Node * node) {
children[ind] = node;
}
};
class Trie {
private: Node * root;
public:
Trie() {
root = new Node();
}
public:
void insert(int num) {
Node * node = root;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (!node -> containsKey(bit)) {
node -> put(bit, new Node());
}
node = node -> get(bit);
}
}
public:
int findMax(int num) {
Node * node = root;
int maxNum = 0;
for (int i = 31; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node -> containsKey(!bit)) {
maxNum = maxNum | (1 << i);
node = node -> get(!bit);
} else {
node = node -> get(bit);
}
}
return maxNum;
}
};
vector < int > maxXorQueries(vector < int > & arr, vector < vector < int
>> & queries) {
vector < int > ans(queries.size(), 0);
vector < pair < int, pair < int, int >>> offlineQueries;
sort(arr.begin(), arr.end());
int index = 0;
for (auto & it: queries) {
offlineQueries.push_back({
it[1],
{
it[0],
index++
}
});
}
sort(offlineQueries.begin(), offlineQueries.end());
int i = 0;
int n = arr.size();
Trie trie;
for (auto & it: offlineQueries) {
while (i < n && arr[i] <= it.first) {
trie.insert(arr[i]);
i++;
}
if (i != 0) ans[it.second.second] = trie.findMax(it.second.first);
else ans[it.second.second] = -1;
}
return ans;
}
int main() {
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector < int > arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
vector < vector < int >> queries;
for (int i = 0; i < m; i++) {
vector < int > temp;
int xi, ai;
cin >> xi >> ai;
temp.push_back(xi);
temp.push_back(ai);
queries.push_back(temp);
}
vector < int > ans = maxXorQueries(arr, queries);
for (int j = 0; j < ans.size(); j++) {
cout << ans[j] << " ";
}
cout << endl;
}
}
Input:
2
5 2
0 1 2 3 4
1 3
5 6
1 1
1
1 0
Output:
3 7
-1
Time Complexity: O(Q * N)