#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int bit[32];
int n, num[5211314];
struct Trie {
int trie[5211314][2], tot = 1;
inline void Insert(int a) {
int p = 1;
for (int i = 30; i >= 0; -- i){
//num[i] < 2^31 所以只用开到 30
bool flag = (bit[i] & a);
if (trie[p][flag] == 0) {
trie[p][flag] = ++ tot;
}
p = trie[p][flag];
}
}
inline int Query() {
int final = 0;
for (int i = 1; i <= n; ++ i) {
int now = 0, p = 1;
//遍历每一个数找最大maxn
//因为异或是相同为1不同为0
//所以在同一位置贪心找不一样的数(若num[i]为0则找1,若num[i]为1则找0)
for (int j = 30; j >= 0; -- j) {
bool flag = !(bit[j] & num[i]);
if (trie[p][flag] != 0) {
//若有不同的
p = trie[p][flag];
now += flag;
}
else {
//若没有不相同的
p = trie[p][!flag];
now += (!flag);
}
if (j != 0) now <<= 1;
}
final = max(final, (num[i] ^ now));
//更新
}
return final;
}
}tree;
int main() {
bit[0] = 1;
for (int i = 1; i <= 31; ++ i) {
bit[i] = (bit[i - 1] << 1);
}
scanf("%d", &n);
for (int i = 1; i <= n; ++ i) {
scanf("%d", &num[i]);
//记录每一个数
tree.Insert(num[i]);
}
cout << tree.Query() << endl;
return 0;
}
标签:XOR,int,trie,flag,num,Largest,Pair,bit,include
From: https://www.cnblogs.com/jueqingfeng/p/17476149.html