跳到正文

题解

题解 P17204 「DLESS-6」XOR and MEX

zsz_qvq约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月9日
收录
2026年8月9日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P17204

版本

  1. v1当前

前言

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

题意

给定长度为 nn 的序列 aa,定义:

f(a,x)=mex⁡(a1⊕x,a2⊕x,…,an⊕x)f(a, x) = \operatorname{mex}(a_{1} \oplus x, a_{2} \oplus x, \dots, a_{n} \oplus x)

求:

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

思路

Sov.1—暴力枚举

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

Sov.2—缩小范围

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

Sov.3—再缩范围

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

代码

C++
#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;
}
原文