题目链接
http://noi-test.zzstep.com/contest/0x10%E3%80%8C%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E3%80%8D%E4%BE%8B%E9%A2%98/1602%20The%20XOR%20Largest%20Pair
分析
将每个整数对应的二进制串建成Trie树,在插入一个数前,在Trie树中检索该数,每次尽量沿与当前位不同的走。
AC代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
inline int read() {
int num = 0;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9')
num = num * 10 + c - '0', c = getchar();
return num;
}
const int maxn = 1e5 + 5;
struct Trie {
int ch[32 * maxn][2], tot;
Trie() {
memset(ch[0], 0, sizeof(ch[0]));
tot = 0;
}
int add() {
++tot;
memset(ch[tot], 0, sizeof(ch[tot]));
return tot;
}
void insert(int x) {
int p = 0;
for (int i = 30; i >= 0; --i) {
if (!ch[p][(x >> i) & 1]) ch[p][(x >> i) & 1] = add();
p = ch[p][(x >> i) & 1];
}
}
int query(int x) {
int p = 0, ans = 0;
for (int i = 30; i >= 0; --i) {
if (!ch[p][(x >> i) & 1] && !ch[p][((x >> i) & 1) ^ 1])
break;
if (ch[p][((x >> i) & 1) ^ 1]) {
p = ch[p][((x >> i) & 1) ^ 1], ans |= 1 << i;
}
else p = ch[p][(x >> i) & 1];
}
return ans;
}
} trie;
int main() {
int n = read(), ans = 0;
for (int i = 1; i <= n; ++i) {
int x = read();
ans = max(ans, trie.query(x));
trie.insert(x);
}
printf("%d", ans);
return 0;
}