CodeForces - 1285D Dr. Evil Underscores
time limit per test: 1 second
memory limit per test: 256 megabytes
input: standard input
output: standard 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 max(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 max(ai⊕X) (1≤i≤n).
Input
The first line contains integer n(1 ≤ n ≤ 10^5).
The second line contains n integers a1,a2,…,an (0 ≤ ai ≤ 2^30-1).
Output
Print one integer — the minimum possible value of max(ai⊕X) (1≤i≤n).
Exanples
input
3 1 2 3
output
2
input
2 1 5
output
4
Note
In the first sample, we can choose X=3.
In the second sample, we can choose X=5.
题目大意
给你n个数字,让你求出一个X,这个X与这n个数字单独异或后的最大值最小。
思路
用01字典树,因为2^30,所以说,深度为30.
我们从根节点开始,由于是二叉树,所以说子节点要么是0,要么是1,根据题目要求,我们肯定要这个值(0或1),如果当前节点的子节点有1,也有0,那么我们就要用(1<<k)加上下一位的最小值(因为是高位到低位)。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <map>
#include <cstring>
#include <sstream>
#include <set>
#include <list>
#include <fstream>
#include <iomanip>
#include <assert.h>
#define ll long long
#define ull unsigned long long
#define pii std::pair<int, int>
#define op \
std::ios::sync_with_stdio(false); \
std::cin.tie(0);
const int INF = 0x3f3f3f3f;
const int maxn = (100000 + 5);
const int mod = (998244353);
int num=0;
int trie[1<<21][2];
void insert(ll x)
{
int pos=0;
for(int i=29;i>=0;i--)
{
int t=(x>>i)&1;
if(!trie[pos][t])
trie[pos][t]=++num;
pos=trie[pos][t];
}
}
int solve(int t,int now)
{
if(t==-1)
return 0;
if(trie[now][0]==0)
return solve(t-1,trie[now][1]);
if(trie[now][1]==0)
return solve(t-1,trie[now][0]);
return (1<<t)+std::min(solve(t-1,trie[now][1]),solve(t-1,trie[now][0]));
}
int main()
{
int n,a;
scanf("%d",&n);
while(n--)
{
scanf("%d",&a);
insert(a);
}
printf("%d",solve(29,0));
return 0;
}