-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_1707_MaxXORWithElementFromArray.cpp
113 lines (102 loc) · 2.78 KB
/
LC_1707_MaxXORWithElementFromArray.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
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
/*
https://leetcode.com/problems/maximum-xor-with-an-element-from-array/
1707. Maximum XOR With an Element From Array
*/
struct TrieNode{
TrieNode* children[2];
bool isEnd;
};
class Trie{
TrieNode *root;
public:
Trie()
{
root = new TrieNode();
}
void insert(int num)
{
TrieNode* ptr = root;
for(int i=31; i>=0; i--)
{
int bit = (num>>i)&1;
if(ptr->children[bit] == nullptr)
ptr->children[bit] = new TrieNode();
ptr = ptr->children[bit];
}
}
int findxor(int num)
{
int xr=0;
TrieNode* ptr = root;
for(int i=31; i>=0; i--)
{
int bit =(num>>i)&1;
if(ptr->children[!bit])
{
xr |= 1<<i;
ptr = ptr->children[!bit];
}
else{
ptr = ptr->children[bit];
}
// cout<<bit<<"->"<<bitset<5>(xr)<<" ";
}
// cout<<num<<" "<<xr<<endl;
return xr;
}
};
class Solution {
public:
static bool sortbysecond(vector<int>& a, vector<int>& b){
return a[1]<b[1];
}
vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
Trie tr;
int n = nums.size(), nq = queries.size();
vector<int> ans(nq, -1);
/*
int i=0;
for(auto &vec: queries) vec.push_back(i++);
sort(queries.begin(), queries.end(), sortbysecond);
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
bool smallExist = false;
for(auto& vec: queries)
{
int xi = vec[0];
int mi = vec[1];
int idx = vec[2];
while(!pq.empty() and pq.top()<= mi)
{
smallExist = true;
// cout<<pq.top()<<" ";
insert(pq.top()); // insert all elements less than m_i
pq.pop();
}
if(smallExist)
ans[idx] = findxor(xi);
}
*/
sort(nums.begin(), nums.end());
vector<pair<int, pair<int, int>>> offlineq;
int idx=0;
for(auto &vec: queries)
offlineq.push_back({vec[1],{vec[0], idx++}});
sort(offlineq.begin(), offlineq.end());
idx=0;
for(auto &oq : offlineq)
{
int mi = oq.first;
int xi = oq.second.first;
int ins = oq.second.second;
while(idx<n and nums[idx] <= mi)
{
// cout<<nums[idx]<<" ";
tr.insert(nums[idx]);
idx++;
}
if(idx != 0)
ans[ins] = tr.findxor(xi);
}
return ans;
}
};