D. Dr. Evil Underscores
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Today, as a friendship gift, Bakry gave Badawy n integers a1,a2,…,an and challenged him to choose an integer X such that the value 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).
Input
The first line contains integer n (1≤n≤105).
The second line contains n integers a1,a2,…,an (0≤ai≤230−1).
Output
Print one integer — the minimum possible value of max1≤i≤n(ai⊕X).
Examples
inputCopy
3
1 2 3
outputCopy
2
inputCopy
2
1 5
outputCopy
4
Note
In the first sample, we can choose X=3.
In the second sample, we can choose X=5.
题意:
给一个数组 a,让你找到一个数 x 使得 x^ai的最大值最小
思路:
比较明显的字典树,可以先把这n 个数存到字典树中,然后一位一位考虑,两种情况;
1.如果当前位只有 0 或者只有 1 ,那只需要选相同的就好了,这样产生的贡献是 0 .(1^1=0, 0^0=0).
2.但如果这一同时存在 0 和 1,那么我们无论选择 0还是1 都会产生(1<<k)的贡献(因为求的是最大),我们无法确定当前位取0还是取 1好,所以我们用 dfs枚举,取较小的那一个。
代码
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=3e6;
int tot=1,tire[maxn][2],cnt[maxn],a[maxn];
void insert(int x){
int p=0,t;
for(int i= 30;i >= 0; i--){
t=((x>>i)&1);
if(!tire[p][t]) tire[p][t]=tot++;
p=tire[p][t];
}
cnt[p]=x;
}
int dfs(int k,int p){
if(k<0) return 0;
if(!tire[p][0]) return dfs(k-1,tire[p][1]);
if(!tire[p][1]) return dfs(k-1,tire[p][0]);
return (1<<k)+min(dfs(k-1,tire[p][0]),dfs(k-1,tire[p][1]));
}
int main (){
int n;
cin>>n;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
insert(a[i]);
}
printf ("%d\n",dfs(30,0));
}