---
id: 271
lang: en
translation_of: index.md
source_sha256: 7f2f6707522f9a9c0f3120d7b1a784ca664097f9062f279636e3d7d5e5e6d6c1
title: "CH1602: The XOR Largest Pair — Solution"
description: "How do we find a pair of numbers with the largest XOR? We can consider building a Trie from the highest bit down to the lowest."
tags: ["OI","Strings","Trie","Bitwise Operations"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The inline formula $0或1$ contains the Chinese word 或 (“or”) outside any \\text{…}; TeX is kept identical, so it reads “0 or 1”."
  - "上一条 (“the previous item”) refers to the first bullet point; rendered as “the previous point”."
---

## 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:

<!--more-->

- 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

```cpp
// 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;
}
```
