D. Dr. Evil Underscores---字典树+dp/贪心
作者:互联网
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.
题意:找出一个x,使得x^a[i]的值最大。
解析:一般求异或的就想到字典树。一般取0,我们要往1走,取1要往0走。这样才能取到最大值。但是这里遇到左右子树,我们需要贪心选择走哪个最优策略。因为求得是最大值中的最小,所以我们需要比较左右子树的最小值
#include<bits/stdc++.h>
using namespace std;
vector<int> a;
int x;
int slove(vector<int> a,int k)
{
if(a.size()==0||k<0) return 0; //当没有位数了
vector<int> p1,p2;
for(int i=0;i<a.size();i++)
{
if((a[i]>>k)&1) p1.push_back(a[i]); //每个数的每位。是1的存在p1,是0的存在p2
else p2.push_back(a[i]);
}
if(p1.size()==0) return slove(p2,k-1);
if(p2.size()==0) return slove(p1,k-1);
return (1<<k)+min(slove(p1,k-1),slove(p2,k-1)); //当前的贡献值+左右子树的最小贡献值。
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
a.push_back(x);
}
cout<<slove(a,30)<<endl;
}
AKone123456
发布了258 篇原创文章 · 获赞 5 · 访问量 3123
私信
关注
标签:p2,p1,return,int,Underscores,Evil,ai,choose,Dr 来源: https://blog.csdn.net/qq_43690454/article/details/103955909