forked from Ayushsinhahaha/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxiXor
103 lines (90 loc) · 2.15 KB
/
maxiXor
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
#include<bits/stdc++.h>
class TrieNode{
public:
int data;
TrieNode** children;
TrieNode(int bit){
data = bit;
children = new TrieNode*[2];
children[0] = NULL;
children[1] = NULL;
}
};
class Trie{
TrieNode* root;
public:
Trie(){
root = new TrieNode(0);
}
void insert(TrieNode* root, int num){
TrieNode* child;
for(int i=31;i>=0;i--){
int bit = ((1<<i)&num);
if(bit>0)bit=1;
if(root->children[bit]){
root = root->children[bit];
}
else{
child = new TrieNode(bit);
root->children[bit] = child;
root = child;
}
}
}
void insert(int num){
insert(root, num);
}
int maxXor(TrieNode* root, int num){
int ans = 0;
TrieNode* child;
for(int i=31;i>=0;i--){
int bit = ((1<<i)&num);
if(bit>0)bit=1;
if(root->children[1-bit]){
ans +=((1<<i));
root = root->children[1-bit];
}
else{
//child = new TrieNode(bit);
child = root->children[bit];
root = child;
}
}
return ans;
}
int maxXor(int num){
return maxXor(root, num);
}
};
vector<int> maxXorQueries(vector<int> &arr, vector<vector<int>> &queries){
// Write your coode here.
Trie dummy;
int q = queries.size();
vector<int> ans(q, -1);
// {xi,{A[i],index}}
vector<pair<int,pair<int, int>>> aqq(q);
int i=0;
for(auto it : queries){
aqq[i]={it[1],{it[0], i}};
i++;
}
sort(arr.begin(),arr.end());
sort(aqq.begin(),aqq.end());
int j=0;
i=0;
int n = arr.size();
while(i<q){
int ai = aqq[i].first;
while(j<n && arr[j]<=ai){
dummy.insert(arr[j]);
j++;
}
int temp = -1;
if(j>0){
temp = dummy.maxXor(aqq[i].second.first);
}
ans[aqq[i].second.second]=temp;
i++;
}
return ans;
}