最大异或对

Trie树的应用

#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int son[N * 31][2];
int idx;
int a[N];
void insert(int x)
{
    int p = 0;
    for(int i = 30; i >= 0; i --)
    {
        int u = x >> i & 1;
        if(!son[p][u])son[p][u] = ++ idx;
        p = son[p][u];
    }
}

int qurry(int x)
{
    int p = 0, res = 0;
    for(int i = 30; i >= 0; i --)
    {
        int u = x >> i & 1;
        if(son[p][!u]){
            p = son[p][!u];
            res = res * 2 + !u;
        }
        else {
            p = son[p][u];
            res = res * 2 + u;
        }
    }
    return res;
}
int main()
{
    int n;
    cin >> n;
    for(int i = 1; i <= n; i ++)cin >> a[i];
    
    int ans = 0;
    for(int i = 1; i <= n; i ++)
    {
        insert(a[i]);//因为题目只需要枚举两个数之间异或的结果,异或具有交换律,所以可以先插入在做
        
        int t = qurry(a[i]);
        
        ans = max(a[i] ^ t, ans);
    }
    cout << ans<<endl;
    return 0;
}

链接

数据结构 文章被收录于专栏

数据结构

全部评论

相关推荐

可以不说话:笔试a了3道半,今天说是挂了😭😭
投递汇丰科技等公司9个岗位
点赞 评论 收藏
分享
03-16 22:00
武汉大学 C++
幸福的小熊猫想要offer:我阿里投的 c++岗,面试官说自己是做 java 的,c++这辈子才有了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务