[CSU1216]异或最大值

最大异或和

题解

把二进制数放在树上,然后枚举每个数,根据贪心的思路在trie树上尽量往反方向就好了
单纯的为了写一下trie

#include<bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long LL;
typedef pair<int,int> PII;
#define X first
#define Y second
const int maxn=100010;
int n,a[maxn],ch[32*maxn][2],val[32*maxn],sz,ans;
void insert(int x)
{
    int now=0;
    for(int i=31;i>=0;i--)
    {
        int c=(x>>i)&1;
        if(!ch[now][c])ch[now][c]=++sz;
        now=ch[now][c];
    }
    val[now]=1;
}
int search(int x)
{
    int res=0,now=0;
    for(int i=31;i>=0;i--)
    {
        int c=(x>>i)&1;
        if(ch[now][c^1])c^=1;
        res|=(c<<i);
        now=ch[now][c];
    }
    return res;
}    
int main()  
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i],insert(a[i]);
    for(int i=1;i<=n;i++)ans=max(ans,a[i]^search(a[i]));
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/FYH-SSGSS/p/12273979.html