D. Dr. Evil Underscores
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.
题意:给你n个数,让找到一个数,使这个数分别与这n个数进行亦或操作,会得到n个亦或后的数,使这些亦或后的数中的最大值最小。
解题思路:我们在二进制下进行操作,最多有30位,所以我们直接从第30位进行考虑,对每一位来讲,只会有两种情况,一种是对于所有的数,这位都是1或者都是0,另一种是这位既有1还有0,对于前者,我们直接return solve(l,bit-1)或者return solve(r,bit-1),因为我们最后所求的就是亦或后的最大值,所以在这里不用加1<<bit,对于第二种既有1又有0的情况,我们需要加1<<bit 。 因为我们选择的数在这位不论是1还是0,都会是亦或后的最大值增加1<<bit,故选1还是选0我们使用return min(solve(l,bit-1),solve(r,bit-1))+(1<<bit) . 这样就保证了考虑了所有情况。
这里引用官方题解:
#include <bits/stdc++.h>
using namespace std;
int n;
vector <int> a;
int solve(vector <int> &c, int bit){
if(a.size() == 0 || bit < 0) return 0;
vector <int> l, r;
for(auto &i : c){
if(((i >> bit) & 1) == 0) l.push_back(i);
else r.push_back(i);
}
if(l.size() == 0) return solve(r, bit - 1);
if(r.size() == 0) return solve(l, bit - 1);
return min(solve(l, bit - 1), solve(r, bit - 1)) + (1 << bit);
}
int main(){
cin >> n;
a.resize(n);
for(auto &i : a) cin >> i;
cout << solve(a, 30) << endl;
}