Solution for Codeforces 1285D - Dr. Evil Underscores

Almost

Solution #

Let’s start with the highest bit since it’s the most significant. We need to divide elements into two groups, one with elements which is 11 on this bit and the other with elements which is 00 on this bit. If either group is empty, we can always assign 0 or 1 to this bit to make this bit 0 in the answer and we can just proceed to the next bit, otherwise this bit is always 1. In order to know which value to assign we will solve the same problem recursively for each of the groups for the next bit. Let the answer for the two groups be ans1ans_1 and ans0ans_0 and the current bit is ii the answer would be 2i+min(ans1,ans0)2^i+\min(ans_1,ans_0).

Code #

#include <bits/stdc++.h>
 
using namespace std;
vector<int> a;
int dfs(vector<int> v,int idx){
    if(v.empty()) return 0;
    if(idx==-1) return 0;
    vector<int> a,b;
    for(auto it:v){
        if(it&(1<<idx)) a.pb(it);
        else b.pb(it);
    }
    if(a.empty()) return dfs(b,idx-1);
    if(b.empty()) return dfs(a,idx-1);
    return min(dfs(a,idx-1),dfs(b,idx-1))+(1<<idx);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
	int n;
    cin>>n;
    a.resize(n);
    for(int& it:a) cin>>it;
    cout<<dfs(a,30);
    return 0;
}