codeforces-1285D(字典樹)

Dr. Evil Underscores

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 \(max_{1≤i≤n}\)(ai⊕X).

Input
The first line contains integer n (1≤n≤\(10^5\)).

The second line contains n integers a1,a2,…,an (0≤ai≤\(2^{30}\)−1).

Output
Print one integer — the minimum possible value of max1≤i≤n(\(a_i\)⊕X).

Examples

input

Copy

3
1 2 3

output

Copy

2

input

Copy

2
1 5

output

Copy

4

Note

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

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

題意:給定n個數,要求你設定一個X,這個X與每個數異或後所得的結果最小,並且這個X要儘可能的大,輸出這個異或出的最小的結果

思路:採用異或字典樹即可,由於題目給定的數據範圍是 \(2^{30}-1\),所以只需要將字典樹的深度設置爲31位即可,

因爲異或是不進位的加法運算,將每一個數都構造爲30位的二進制存放在字典樹中,接着從第29位開始向低位構造異或出的結果,因爲要求異或結果ans儘可能的小而構造的X儘可能的大,對於第i位,如果在n個數中第i位0和1都存在,那麼ans就一定要加上\(2^i\),之後再對子樹答案取min即可。入宮第i位只有0或1,直接取反就行了。時間複雜度是O{logmax\(a_i\)}

代碼:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cctype>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<vector>

using namespace std;
using ll = long long;
const ll N = 1e6;
const double PI = acos(-1.0);
#define Test ll tesnum;tesnum = read();while(tesnum--)
ll read();
int cnt = 1;
int tri[1<<21][2];
void insert(int x)
{
    int p = 1;
    for(int i = 29; i >= 0; i--){
        int ch = (x >> i)&1;
        if(tri[p][ch]==0){
            tri[p][ch] = ++cnt;
        }
        p = tri[p][ch];
    }
}

int solve(int modo,int now)
{
    if(modo==-1)
        return 0;
    if(tri[now][0]==0)
        return solve(modo-1,tri[now][1]);
    else
    if(tri[now][1]==0)
        return solve(modo-1,tri[now][0]);
    else
        return (1<<modo)+min(solve(modo-1,tri[now][1]),solve(modo-1,tri[now][0]));
}
int main()
{
    int n,a;
    cin>>n;
    while(n--)
    {
        cin>>a;
        insert(a);
    }
    cout<<solve(29,1)<<endl;
    return "BT7274", NULL;
}

inline ll read() {
    ll hcy = 0, dia = 1;char boluo = getchar();
    while (!isdigit(boluo)) {if (boluo == '-')dia = -1;boluo = getchar();}
    while (isdigit(boluo)) {hcy = hcy * 10 + boluo - '0';boluo = getchar();}
    return hcy * dia;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章