mirror of
https://git.sb/baoshuo/OI-codes.git
synced 2024-11-08 15:18:46 +00:00
143. 最大异或对
https://www.acwing.com/problem/content/submission/code_detail/7682567/
This commit is contained in:
parent
16a05f1a38
commit
d08421fad2
55
AcWing/143/143.cpp
Normal file
55
AcWing/143/143.cpp
Normal file
@ -0,0 +1,55 @@
|
||||
#include <bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int n, a[100005], ans;
|
||||
|
||||
struct node {
|
||||
int val;
|
||||
node* next[2];
|
||||
|
||||
~node() {
|
||||
for (auto i : next) {
|
||||
delete i;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void insert(node* root, int x, int b) {
|
||||
if (!x) {
|
||||
root->val++;
|
||||
return;
|
||||
}
|
||||
if (root->next[(x >> b) & 1] == nullptr) root->next[(x >> b) & 1] = new node();
|
||||
insert(root->next[(x >> b) & 1], x - (((x >> b) & 1) << b), b - 1);
|
||||
}
|
||||
|
||||
int search(node* root, int x) {
|
||||
int res = 0;
|
||||
node* p = root;
|
||||
for (int i = 30; i >= 0; i--) {
|
||||
if (p == nullptr) break;
|
||||
if (p->next[!((x >> i) & 1)] != nullptr) {
|
||||
res += 1 << i;
|
||||
p = p->next[!((x >> i) & 1)];
|
||||
} else {
|
||||
p = p->next[(x >> i) & 1];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
int main() {
|
||||
node* root = new node();
|
||||
cin >> n;
|
||||
for (int i = 0; i < n; i++) {
|
||||
cin >> a[i];
|
||||
insert(root, a[i], 30);
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
ans = max(ans, search(root, a[i]));
|
||||
}
|
||||
cout << ans << endl;
|
||||
delete root;
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user