题目:
在给定的 N 个整数 A1,A2……AN 中选出两个进行 xor(异或)运算,得到的结果最大是多少?
输入格式
第一行输入一个整数 N。
第二行输入 N 个整数 A1~AN。
输出格式
输出一个整数表示答案。
数据范围
1≤N≤105,
0≤Ai<231
输入样例:
3
1 2 3
输出样例:
3
#include <iostream>
#include <algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
using namespace std;
const int N = 100010, M = 3000010;
int n;
int a[N], son[M][2], idx; // 300 0000 是 31 * 10 0000
// son [M][2] 2是 0,1 分支 every number max length is 31
void insert(int x)
{
int p = 0;
for (int i = 30; ~i; i--)
{
int &s = son[p][x >> i & 1]; // judge i bit is 0 or 1
if (!s) s = ++ idx; // if that position is none, then create one index
p = s; // p -> s
}
}
int search(int x)
{
int p = 0, res = 0;
for (int i = 30; ~i ; i --)
{
int s = x >> i & 1;
if (son[p][!s]) // find max xor, so !s is max
{
res += 1 << i; // value of max xor result,
p = son[p][!s]; // p goto there to find next bit
}
else
{ // have no xor perfect, so find same bit to go
// res += 0 << i; // value of max xor result, the xor is 0 so can no operate
p = son[p][s]; // p goto there to find next bit
}
}
return res;
}
int main()
{
IOS;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
insert(a[i]);
}
int res = 0;
for (int i = 0; i < n; i ++) res = max(res, search(a[i]) );
cout << res;
return 0;
}