CH1602: The XOR Largest Pair — Solution
Main Idea
How do we find a pair of numbers whose XOR value is the largest? Let's start from binary arithmetic (bitwise operations) itself. If we want to make sure the \(Xor\) value is larger, then we need as many \(1\)s as possible. Besides that, the position of the \(1\)s also matters a lot: in some cases, nearer the front is better. We can consider building a Trie starting from the highest bit down to the lowest bit. Let \(num[i]\) denote bit \(i\)'s \(0或1\) state. After building the Trie, we compute, for each number, the largest XOR value it corresponds to. Our strategy is:
- We have already moved from bit 30 down to bit \(i\), and the corresponding digit we hope for is \(1\; xor \; 1\). If this value exists at the node, then recurse downward as normal.
- If the digit we hope for is not there, then we can only pick the same digit, and when recursing downward, note that the endpoint is different from the previous point.
For the details, see the code:
Code
// CH1602.cpp
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 100000 * 40;
int trie[maxn][2], arr[maxn], n, current = 2;
void insert(int num)
{
int pnode = 1;
for (int i = 30; i >= 0; i--)
{
int bit = (num >> i) & 1;
if (trie[pnode][bit] == 0)
trie[pnode][bit] = current++;
pnode = trie[pnode][bit];
}
}
int getBiggest(int num)
{
int ans = 0, pnode = 1;
for (int i = 30; i >= 0; i--)
{
int bit = (num >> i) & 1;
if (trie[pnode][bit ^ 1] != 0)
pnode = trie[pnode][bit ^ 1], ans |= (1 << i);
else
pnode = trie[pnode][bit];
}
return ans;
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]), insert(arr[i]);
int ans = 0;
for (int i = 0; i < n; i++)
ans = max(ans, getBiggest(arr[i]));
printf("%d", ans);
return 0;
}