本文共 1307 字,大约阅读时间需要 4 分钟。
在给定的一组整数中,找到两个数,使得它们的异或结果达到最大值。这个问题可以通过Trie树结构高效地解决。
#include#include using namespace std;int n, x, num, s[3200020][40], ans, now, root, trie[3200020][40];void convert(int x, int cnt) { for (int i = 31; i >= 0; i--) { s[cnt][i] = (x >> i) & 1; }}int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &x); convert(x, i); root = 0; for (int j = 31; j >= 0; j--) { if (!trie[root][s[i][j]]) { trie[root][s[i][j]] = ++num; } root = trie[root][s[i][j]]; } } for (int i = 1; i <= n; i++) { root = now = 0; for (int j = 31; j >= 0; j--) { if (trie[root][1 - s[i][j]]) { now += (1 << j); root = trie[root][1 - s[i][j]]; } else { root = trie[root][s[i][j]]; } } ans = max(ans, now); } printf("%d", ans);}
convert函数将整数转换为二进制数组,并存储在s数组中。n,然后逐个读取每个数,进行二进制转换,并构建Trie树。ans。这个方法通过Trie树高效地解决了最大异或对问题,时间复杂度为O(32 * n),适合处理较大的数据集。
转载地址:http://ryiq.baihongyu.com/