1. 程式人生 > >異或最大 [0/1trie]

異或最大 [0/1trie]

傳送門

每個整數看著32位的二進位制01串,將N個數從高位到低位依次插入到一個01trie中。

考慮插入第i個數,相當於在trie中進行依次檢索,根據xor相同為0,不同為1的特點,貪心的每次走與Ai當前位相反的指標,

如果沒有相反的節點則走相同的,這樣就可以得到與Ai做XOR運算的最大Aj

#include<bits/stdc++.h>
#define N 100050*30
using namespace std;
int ch[N][2],val[N],n,ans,tot;
void Insert(int x){
	int now = 0;
	for(int i=31;i>=0;i--){
		int pos = ((x>>i)&1);
		if(!ch[now][pos]) ch[now][pos]=++tot;
		now = ch[now][pos];
	} val[now] = x;
}
int Quary(int x){
	int now = 0;
	for(int i=31;i>=0;i--){
		int pos = ((x>>i)&1)==0;
		if(ch[now][pos]) now = ch[now][pos];
		else now = ch[now][pos^1]; 
	} return val[now];
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		int x; scanf("%d",&x);
		ans = max(ans,x^Quary(x)); Insert(x);
	} printf("%d",ans); return 0;
}