DFS-B - Dr. Evil Underscores

B - Dr. Evil Underscoresios

Today, as a friendship gift, Bakry gave Badawy nn integers a1,a2,,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1in(aiX)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 max1in(aiX)max1≤i≤n(ai⊕X).ide

Input函数

The first line contains integer nn (1n1051≤n≤105).atom

The second line contains nn integers a1,a2,,ana1,a2,…,an (0ai23010≤ai≤230−1).spa

Output.net

Print one integer — the minimum possible value of max1in(aiX)max1≤i≤n(ai⊕X).code

Examplesorm

Input
3
1 2 3
Output
2
Input
2
1 5
Output
4

Notexml

In the first sample, we can choose X=3X=3.

In the second sample, we can choose X=5X=5.

  题目大意:在给出的n个整数中选出一个整数,使得剩下全部数与这个数的获得的最大异或结果最小

  

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<vector>
 4 using namespace std;
 5 
 6 vector<int> v;
 7 const int N = 1e5 + 50;
 8 int n, x, maxn, cnt;
 9 
10 int DFS(int cnt, vector<int> v){
11     if(v.size()==0 || cnt<0)    return 0;//数组中没有整数或二进制有负数位天然不用再考虑 
12     vector<int> v1, v0;//注意这是在函数中定义的局部的不定长数组 
13     for(int i=0; i<v.size(); i++){
14         //判断某数的二进制的某一位上,是1即插入v1,是0即插入v0 
15         if((v[i]>>cnt) & 1)        v1.push_back(v[i]);
16         else                    v0.push_back(v[i]);
17     }
18     //若全部整数的二进制在这一位上均为同一个数(无论是0仍是1)均可以用0或1使得其异或结果均为0,从而达到使异或结果最小的目的 
19     if(v1.empty())        return DFS(cnt-1, v0);
20     else if(v0.empty())    return DFS(cnt-1, v1);
21     //若是全部整数的二进制在这一位上不可避免的既有1有有0,则其异或结果能够使1也能够是0,而结果是取最大的异或结果,即1 
22     else                return min(DFS(cnt-1, v1), DFS(cnt-1, v0)) + (1<<cnt);
23 }
24 
25 int main(){
26     scanf("%d", &n);
27     for(int i=0; i<n; i++){
28         scanf("%d", &x);
29         v.push_back(x);
30         if(x > maxn)    maxn = x;
31     }
32     //找到其中最大的数,并统计出其二进制有几位 
33     while(maxn){
34         maxn >>= 1;
35         cnt ++;
36     }
37     printf("%d",DFS(cnt, v));
38     return 0;
39 }

(1)即便题目放在搜索训练中,我也想不到和搜索有什么关系。其实若是用最简单暴力的方法去作,就是无脑遍历呗,必然超时的原始人操做,这里所用的方法,就是函数递归,递归到头,省时省力。

(2)由于题目中的操做是异或,全部须要将所给的整数,进行二进制处理,而思路也注释在了代码中:若是全部的整数的二进制形式,在某一位上均位同一个数,则很轻易地能用另外一个数,使这一位上的异或结果均为0;相反的,若是全部整数在这一位上的数字既有1又有0,也就是无论怎么样,异或结果都会碰到1,题目找到是最大异或结果的最小值,因此当碰到这种结果时只能乖乖取1。

(3)DFS的递归。从最大整数的最高位开始,一位一位地向后递归,在每一位上都获得最理想的异或结果,合起来,就是所求的最大异或结果的最小值。

相关文章
相关标签/搜索