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 max1≤i≤n(ai⊕X)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)max1≤i≤n(ai⊕X).ide
Input函數
The first line contains integer nn (1≤n≤1051≤n≤105).atom
The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).spa
Output.net
Print one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).code
Examplesorm
Input3 1 2 3Output2Input2 1 5Output4Notexml
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的遞歸。從最大整數的最高位開始,一位一位地向後遞歸,在每一位上都獲得最理想的異或結果,合起來,就是所求的最大異或結果的最小值。