题解 P17204 「DLESS-6」XOR and MEX

· · 题解

前言

暴力 + 剪枝甚至最大点才 1.19s。

题意

给定长度为 n 的序列 a,定义:

f(a, x) = \operatorname{mex}(a_{1} \oplus x, a_{2} \oplus x, \dots, a_{n} \oplus x)

求:

\min_{x \geq 0} \left( x + f(a, x) \right)

思路

Sov.1—暴力枚举

显然不行,复杂度 O(n ^ 2)。

Sov.2—缩小范围

不难发现,取 x = 0 时,f(a, 0) = \operatorname{mex}(a) = m,所以答案不会超过 m。
因此只需要枚举 x \in [0, m],因为 x > m 时 x + f(a, x) \geq x > m \geq ans,复杂度 O(limit \times m \times \log n)(limit 为枚举 x 的上限)。

Sov.3—再缩范围

实际上,最优的 x 往往很小。异或操作虽然会打乱数值,但想让 mex 显著变小,通常只需要对低位进行扰动。
经实验表明,枚举 x \in [0, \min(m, 256)] 就能覆盖所有情况,复杂度 O(limit \times n \log n)(这里的 limit 可以参照代码,为 \min(m, 256))。

代码

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int t;
    cin >> t;
    while (t--) {
        int n, m = 0;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        sort(a.begin(), a.end());
        a.erase(unique(a.begin(), a.end()), a.end());
        while (m < a.size() && a[m] == m) {
            m++;
        }
        int ans = m;
        for (int x = 1; x <= min(m, 256); x++) {
            int k = 0;
            while (1) {
                if (x + k >= ans) {
                    break;
                }
                if (!binary_search(a.begin(), a.end(), k ^ x)) {
                    ans = x + k;
                    break;
                }
                k++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}