Today, as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.
As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).
Input
The first line contains integer nn (1≤n≤1051≤n≤105).
The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).
Output
Print one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).
Examples
input
3 1 2 3
output
2
input
2 1 5
output
4
Note
In the first sample, we can choose X=3X=3.
In the second sample, we can choose X=5X=5.
题意: 给出n个整数,寻找另外一个整数,使它与这些数中的最大异或值最小,输出这个最小值。
分析: 最终只需要输出最大异或值的最小值,因此只需要考虑如何使最大异或值最小即可。将各数字加入01字典树后,任取一整数求最大异或值,可以发现结果中某位数值只与当前节点子节点有关。如果当前节点两个子节点都存在,那不管下一位取0还是1异或起来一定为1。如果当前节点只有一个子节点存在,那下一位一定会取相同数字,异或起来为0。用一遍dfs求出最小值即可。
具体代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
int son[3000005][2], idx, cnt[3000005];//cnt[i]记录i节点有几个子节点
void insert(int x)
{
int now = 0;
for(int i = 29; i >= 0; i--)
{
int t = (x>>i)&1;
if(!son[now][t])
{
son[now][t] = ++idx;
cnt[now]++;
}
now = son[now][t];
}
}
int dfs(int now, int step, int num)
{
if(step == 30)
return num;
if(cnt[now] == 1)//如果当前节点有一个子节点
if(son[now][1])
return dfs(son[now][1], step+1, num);
else
return dfs(son[now][0], step+1, num);
else//如果当前节点有两个子节点
return min(dfs(son[now][1], step+1, num|(1<<(29-step))), dfs(son[now][0], step+1, num|(1<<(29-step))));
}
signed main()
{
int n, t;
cin >> n;
for(int i = 1; i <= n; i++)
{
scanf("%d", &t);
insert(t);
}
cout << dfs(0, 0, 0);
return 0;
}