[Ybtoj Chapter 9 Example 2] The largest XOR pair [Trie tree]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem-solving ideas

Taking into account the nature of XOR: the higher the digits of two binary numbers appear, the larger the number after XOR. We consider using Trie TrieT r i e numbers solve this problem, we first treat n binary numbers as strings and store them inTrie TrieT r i e tree.

Consider choosing a number a, and find a b among n numbers so that the XOR value of the two is greater.

Consider judging from high to low.
If aaa specific firstiii bit is1, p 1, p. 1 , P of000 pointer exists, then followppp of0 0The 0 pointer goes down, if it does not exist, it goes down along the 1 pointer of p. Ifaaa specific firstiii bit is0 00 is the same.


Code

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

int n,a[3200010],trie[3200010][2],tot=1,ans;

void insert(int x){
    
    
	int p=1,c;
	for(int i=31;i>=0;i--){
    
    
		c=((x>>i)&1);
		if(!trie[p][c])
			trie[p][c]=++tot;//建树
		p=trie[p][c];
	}
}

int get(int x)
{
    
    
	int p=1,c,lyx=0;
	for(int i=31;i>=0;i--){
    
    
		if(((x>>i)&1)==1)
			c=0;
		else c=1;
		if(trie[p][c])//这一位不同
			lyx+=(int)(1<<i);//加上贡献
		else c=((x>>i)&1);
		p=trie[p][c];
	}
	return lyx;
}

int main(){
    
    
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
    
    
		scanf("%d",&a[i]);
		insert(a[i]);	
	} 
	for(int i=1;i<=n;i++)
		ans=max(ans,get(a[i]));
	printf("%d",ans);
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/115014991