The XOR Largest Pair

传送门

题目大意:给n数字,选两个数使得它们异或和最大

思路:01trie树

暴力n方tle

我们可以建一颗只有01的二叉树,建树后,每个数去树上跑一下,看匹配后异或值最大的结果即可,O(n)复杂度

我们可以边建边跑,因为对于有最大值异或和的数x和y,xy总会去匹配的,x先去匹配,y后去匹配总会匹配到x的,反之同理

(做的时候没想到字典树TwT,也是只练过一题字典树的缘故。有用二进制的每一位二分去找最优匹配的数,但特殊情况太多了不会写,只过了91%,太菜了555)

 

#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
using namespace std;
#define _for(i,a,b) for(int i=(a) ;i<=(b) ;i++)
#define _rep(i,a,b) for(int i=(a) ;i>=(b) ;i--)
#define mst(v,s) memset(v,s,sizeof(v))
#define pb push_back
#define IOS ios::sync_with_stdio(false)
#define int long long
#define INF 0x3f3f3f3f3f3f3f3f
#define all(v) v.begin(),v.end()
typedef long long ll;
const int N =1e6+10;
int n,k;
int a[N],tr[N*32][2];//建树内存只要每个点*31,,存二进制即可
int tot;
ll ans;
void Q(int x)
{
    int pos=0;
    int sum=0;
    _rep(i,30,0)
    {
        int k = x>>i&1;//取最后一位
        if( tr[pos][k^1] ) pos = tr[pos][k^1],sum |= 1<<i;
        else pos = tr[pos][k];
    }
    ans = max(ans , sum);
}
void build(int x)
{
    int pos=0;
    _rep(i,30,0)
    {
        int k = x>>i&1;//取最后一位
        if( !tr[pos][k] ) tr[pos][k]= ++tot;
        pos = tr[pos][k];
    }
}
signed main()
{
    ///!!!
//    freopen("data.txt","r",stdin);
    //!!!
    IOS;
    cin>>n;
    _for(i,1,n)
    {
        int x;
        cin>>x;
        build(x);
        if( i!=1 ) Q(x);
    }
    cout<<ans<<endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值