题解:CF2218E The 67th XOR Problem

· · 题解

题目说每次选一个数,把剩下的都异或一遍再删掉。

手玩一下:假设数组是 [a, b, c],选 c 删掉,剩下 [a \oplus c, b \oplus c]。再选 b \oplus c 删掉,最后剩下的就是 (a \oplus c) \oplus (b \oplus c)

观察到中间的 c 抵消了,结果就是 a \oplus b

所以不管怎么删,最后剩下的那个数,一定是原数组里某两个数的异或值。

然后就可以把这道题转换成:在数组里找两个数 a_ia_j,求 a_i \oplus a_j 最大的值。

用 0-1 Trie 即可。

代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n, tot, a[N], trie[N * 31][2];
void insert(int x) {
    int p = 0;
    for (int i = 30; i >= 0; i--) {
        int b = (x >> i) & 1;
        if (!trie[p][b]) trie[p][b] = ++tot;
        p = trie[p][b];
    }
}
int query(int x) {
    int p = 0, res = 0;
    for (int i = 30; i >= 0; i--) {
        int b = (x >> i) & 1;
        if (trie[p][!b]) res |= (1 << i), p = trie[p][!b];
        else p = trie[p][b];
    }
    return res;
}
void solve() {
    cin >> n;
    for (int i = 0; i <= tot; i++) trie[i][0] = trie[i][1] = 0;
    tot = 0;
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        if (i > 1) ans = max(ans, query(a[i]));
        insert(a[i]);
    }
    cout << ans << endl;
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T;
    cin >> T;
    while (T--) solve();
    return 0;
}