递归亦或题,D题,D - Dr. Evil Underscores

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值