最大异或对 The XOR Largest Pair 题解

题目链接

一个特别经典的例题。考虑用字典树 Trie 求解。

我们把数的二进制形式(保留前导零)插入字典树 Trie 中,由于要使异或的值最大,所以考虑贪心:先选定一个数,再找一个数,满足在二进制下靠前的数位异或出来的值尽量为 \(1\)

于是,此时的 Trie 就派上用场了,对于选定的数,在 Trie 中,若可以使这一位异或值为 \(1\) 且这一方向有儿子,则往该方向移动,否则向另一个方向移动。

如图所示,若想要为二进制数 \(010\) 查找数,则移动过程为:\(0 \to 1 \to 2 \to 3\),结果为 \(111\)

代码示例:

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e6 + 5;
struct Trie {
	struct point {int son[2];};
	point trie[N];
	int tot;
	inline void insert (int x) {
		int p = 0;
		for (int i = 31; i >= 0; i--) {
			int b = (x >> i) & 1;
			if (!trie[p].son[b])
				trie[p].son[b] = ++tot;
			p = trie[p].son[b];
		}
	}
	inline int find (int x) {
		int ret = 0, p = 0;
		for (int i = 31; i >= 0; i--) {
			int b = (x >> i) & 1;
			if (trie[p].son[b ^ 1]) {
				ret = ret << 1 | 1;
				p = trie[p].son[b ^ 1];
			}
			else {
				ret = ret << 1;
				p = trie[p].son[b];
			}
		}
		return ret;
	}
} t;
int ans, a[N], n;
signed main () {
	ios :: sync_with_stdio (0);
	cin.tie (0), cout.tie (0);
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
		t.insert (a[i]);
	}
	for (int i = 1; i <= n; i++)
		ans = max (ans, t.find (a[i]));
	cout << ans;
	return 0;
}
posted @ 2025-12-26 13:06  暴力算法  阅读(2)  评论(0)    收藏  举报