最大异或对(Trie树)

题目:
在给定的 N 个整数 A1,A2……AN 中选出两个进行 xor(异或)运算,得到的结果最大是多少?

输入格式
第一行输入一个整数 N。

第二行输入 N 个整数 A1~AN。

输出格式
输出一个整数表示答案。

数据范围
1≤N≤105,
0≤Ai<231
输入样例:
3
1 2 3
输出样例:
3

#include <iostream>
#include <algorithm>

#define IOS ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
using namespace std;

const int N = 100010, M = 3000010;

int n;
int a[N], son[M][2], idx;  // 300 0000 是 31 * 10 0000
// son [M][2]  2是  0,1 分支      every number max length is 31
 

void insert(int x)
{
    int p = 0;
    for (int i = 30; ~i; i--)
    {
        int &s = son[p][x >> i & 1];  // judge i bit is 0 or 1 
        if (!s) s = ++ idx;  // if that position is none, then create one index
        p = s;  // p -> s
    }
}

int search(int x)
{
    int p = 0, res = 0;
    for (int i = 30; ~i ; i --)
    {
        int s = x >> i & 1;
        if (son[p][!s])  // find max xor, so !s is max 
        {
            res += 1 << i;  // value of max xor result,
            p = son[p][!s];  // p goto there to find next bit
        }
        else 
        {  // have no xor perfect, so find same bit to go  
            // res += 0 << i;  // value of max xor result, the xor is  0 so can no operate
            p = son[p][s];  // p goto there to find next bit
        }
    }
    return res;
}

int main()
{
    IOS;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        insert(a[i]);
    }
    
    int res = 0;
    for (int i = 0; i < n; i ++) res = max(res, search(a[i]) );
    cout << res;
    
    
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值