The XOR Largest Pair(Tire字典树应用)

时间:2023-03-09 16:23:56
The XOR Largest Pair(Tire字典树应用)

题目链接:传送门

思路:建立一个32位的字典树,对每一个要插入的数字查找它异或的最大值(就是尽量全部二进制的值都相反),

然后获得两个数异或的最大值。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5+;
int ch[maxn*][],tot;
void Insert(int x)
{
int i,u=,c;
for(i=;i>=;i--)
{
c=(x>>i)&;
if(!ch[u][c]) ch[u][c]=++tot;
u=ch[u][c];
}
}
int search(int x)
{
int i,u=,c,o,ans=;
for(i=;i>=;i--)
{
c=(x>>i)&;
o=c^;
if(ch[u][o]) u=ch[u][o],ans=ans<<|;
else u=ch[u][c],ans=ans<<;
}
return ans;
}
int MAX(int x,int y)
{
return x>y?x:y;
}
int main(void)
{
int n,i,x,ans;
while(~scanf("%d",&n))
{
ans=;
memset(ch,,sizeof(ch));
tot=;
for(i=;i<n;i++)
{
scanf("%d",&x);
ans=MAX(ans,search(x));
Insert(x);
}
printf("%d\n",ans);
}
return ;
}