码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-01-23 22:09:04      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:pac   进制   amp   div   set   one   names   const   分享图片   

题目链接:传送门

思路:建立一个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

 

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

标签:pac   进制   amp   div   set   one   names   const   分享图片   

原文地址:https://www.cnblogs.com/2018zxy/p/10311775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!