The XOR Largest Pair(Tire字典树应用)

题目链接:传送门

思路:建立一个32位的字典树,对每一个要插入的数字查找它异或的最大值(就是尽量全部二进制的值都相反),

然后获得两个数异或的最大值。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5+10;
int ch[maxn*32][2],tot;
void Insert(int x)
{
    int i,u=1,c;
    for(i=31;i>=0;i--)
    {
        c=(x>>i)&1;
        if(!ch[u][c]) ch[u][c]=++tot;
        u=ch[u][c];
    }
}
int search(int x)
{
    int i,u=1,c,o,ans=0;
    for(i=31;i>=0;i--)
    {
        c=(x>>i)&1;
        o=c^1;
        if(ch[u][o]) u=ch[u][o],ans=ans<<1|1;
        else u=ch[u][c],ans=ans<<1;
    }
    return ans;
}
int MAX(int x,int y)
{
    return x>y?x:y;
}
int main(void)
{
    int n,i,x,ans;
    while(~scanf("%d",&n))
    {
        ans=0;
        memset(ch,0,sizeof(ch));
        tot=1;
        for(i=0;i<n;i++)
        {
            scanf("%d",&x);
            ans=MAX(ans,search(x));
            Insert(x);
        }
        printf("%d\n",ans);
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/2018zxy/p/10311775.html