[Ybt Advanced 2-4-2] The largest XOR pair

Largest XOR pair

Topic link: ybt efficient advanced 2-4-2

Topic

Give you a bunch of numbers, thirty-one powers less than two, and ask you to choose two numbers to make their exclusive OR greater.
You are required to output this maximum XOR value.

Ideas

What do we consider XOR-the same is 0 0 in binary0 , the difference is1 11

Then we have to maximize the XOR value, which means that the highest digit of the selected number is as different as possible.
Then we can use the Trie tree to make a point have two sons, representing the next one is 0 00 or1 11

But there is a question at this time, do we want the root node to be the highest or the lowest?
Let's imagine that the closer you are to the root node, the higher the priority it matches, which must be the higher the position, and the closer you are to the root node.
If there is no previous bit, add 0 00

Then we build the tree and we are done, and then see how to query a number that matches the previous number.
Then first from the root node is from high to low. For this bit, if there is a difference, choose a different one, otherwise, it depends on whether there is the same. If there are none, then the following is 0 00 , you can withdraw directly.

Of course, only if there are differences can contribute to the answer.

Code

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

struct Trie {
    
    
	int son[2], num;
}trie[3200001];
int n, a[100001], x, tmp[32], nn, now, KK, ans, zhi;

void build() {
    
    //插入
	now = 0;
	for (int i = 31; i >= 0; i--) {
    
    
		if (!trie[now].son[tmp[i]]) {
    
    
			trie[now].son[tmp[i]] = ++KK; 
		}
		now = trie[now].son[tmp[i]];
	}
	trie[now].num++;
}

void find() {
    
    
	now = 0;
	zhi = 0;
	for (int i = 31; i >= 0; i--) {
    
    
		if (!trie[now].son[tmp[i] ^ 1]) {
    
    //没有跟它这一位不同的
			if (trie[now].son[tmp[i]]) {
    
    //只有跟它着一位相同的
				now = trie[now].son[tmp[i]];
			}
			else break;//两个都没有,那后面的肯定是全都没有,不如退出
		}
		else {
    
    //有这一位不同的
			zhi += 1 << i;//加上这一位的贡献
			now = trie[now].son[tmp[i] ^ 1];
		}
	}
	ans = max(ans, zhi);//求出最大值
	return ;
}

int main() {
    
    
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
    
    
		scanf("%d", &a[i]);
		x = a[i];
		nn = 0;
		memset(tmp, 0, sizeof(tmp));
		while (x) {
    
    
			if (x & 1) tmp[nn++] = 1;
				else tmp[nn++] = 0;
			x >>= 1;
		}
		
		find();
		build();
	}
	
	printf("%d", ans);
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/113003234