-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q2.cpp
77 lines (73 loc) · 1.54 KB
/
Q2.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
#include <iostream>
#include <vector>
#include <climits>
#include <cmath>
using namespace std;
#define ll long long int
#define MAXBITS 40
struct TrieNode {
TrieNode* left = NULL; // 0
TrieNode* right = NULL; // 1
};
void insertNode(TrieNode* root, ll x) {
TrieNode* curr = root;
for(ll i=MAXBITS;i>=0;i--) {
ll b = (x>>i)&1;
if(b==1) {
if(!curr->right) {
curr->right = new TrieNode();
}
curr = curr->right;
}
else {
if(!curr->left) {
curr->left = new TrieNode();
}
curr = curr->left;
}
}
}
long searchMaxXOR(TrieNode* root, ll x) {
TrieNode* curr = root;
ll max_XOR = 0;
ll b, i;
for(i=MAXBITS;i>=0;i--) {
b = (x>>i)&1;
if(!curr) {
break;
}
if(b==0) {
if(curr->right) {
max_XOR += pow(2,i);
curr = curr->right;
}
else {
curr = curr->left;
}
}
else {
if(curr->left) {
max_XOR += pow(2,i);
curr = curr->left;
}
else {
curr = curr->right;
}
}
}
return max_XOR;
}
int main() {
ll n, q, x;
cin >> n >> q;
TrieNode* root = new TrieNode;
for(ll i=0;i<n;i++) {
cin >> x;
insertNode(root,x);
}
while(q--) {
cin >> x;
cout << searchMaxXOR(root,x) << endl;
}
return 0;
}