最大异或对

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;
}

链接

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

数据结构

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务