跳到正文

题解

题解:P17621 [qaswed12 OI R1] Xor is Mex

Moonstruck约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年10月6日
收录
2026年10月11日
更新
2026年11月11日
篇幅
约 5 分钟
题目
P17621

版本

  1. v1当前

话说这题的细节还是蛮多的。

首先作答第一问

注意到0⊕1⊕20⊕1⊕2 = mex(0,1,2)mex(0,1,2),所以就输出1个1,1个2,剩下的用0补即可。对于t≤2t\leq 2,显然无解。

然后就是第二问的重头戏了

想要满足条件,必须先满足mex(A1,A2,...,An)=tmex(A_1,A_2,...,A_n)=t,那么序列中必定包含00 ~ t−1t-1。然后再考虑让所有数异或起来等于tt。首先我们先记录00 ~ t−1t-1异或起来的值,记为sumsum。于是分类讨论:

0.对于每种情况,如果最小的∣A∣|A|不小于10610^6,直接无解。总是先输出长度。下面就不叙述了。

1.如果sum=tsum=t,说明已经凑好,直接输出00 ~ t−1t-1

2.如果sum=0sum=0,此时显然不能直接输出tt,于是想到可以用两个异或和为tt的数来代替。选择11,t⊕1t⊕1是一种方案。如果t=1t=1需要特判,输出0,2,30,2,3即可。

3.令x=sum⊕tx = sum⊕t,表示想要加上的目标值。若x<106x<10^6,直接加入即可。否则考虑加上两个数a,ba,b使得a⊕b=xa⊕b=x且max(a,b)<106max(a,b)<10^6。容易想到只给aa留二进制下的最高一位的1,后面全部跟0。则b=x−ab=x-a,这显然是正确的,可以保证大的数尽量小。如果aa仍然不小于10610^6,说明无解,输出−1-1

然后根据上述结论模拟即可,代码比较冗余,这里做个参考

C++
#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    cin >> n;
    //Q1
    if(n <= 2) cout << -1 << endl;
    else {
        for(int i = 1; i <= n - 2; i++) {
            cout << 0 << " ";
        }
        cout << 1 << " " << 2 << endl;
    }
    //Q2
    int sum = 0;
    for(int i = 0; i < n; i++) {
        sum ^= i;
    }
    if(sum == n) {
        if(n >= 1000000) {
            cout << -1 << endl;
            return 0;
        }
        cout << n << " ";
        for(int i = 0; i < n; i++) {
            cout << i << " ";
        }
        cout << endl;
        return 0;
    }
    if(sum == 0) {
        if(n == 1) {
            cout << n + 2 << " " << 2 << " " << 3 << " ";
            for(int i = 0; i < n; i++) cout << i << " ";
            cout << endl;
            return 0;
        }
        int b = n ^ 1;
        if(b >= 1000000 || n + 2 >= 1000000) {
            cout << -1 << endl;
            return 0;
        }
        cout << n + 2 << " ";
        cout << 1 << " " << b << " ";
        for(int i = 0; i < n; i++) {
            cout << i << " ";
        }
        cout << endl;
        return 0;
    } else {
        int x = sum ^ n;
        if(x < 1000000) {
            if(n + 1 >= 1000000) {
                cout << -1 << endl;
                return 0;
            }
            cout << n + 1 << " " << x << " ";
            for(int i = 0; i < n; i++) {
                cout << i << " ";
            }
            cout << endl;
            return 0;
        } else {
            int lg = log2(x);
            int a = 1 << lg;
            int b = x ^ a;
            if(a >= 1000000 || n + 2 >= 1000000) {
                cout << -1 << endl;
                return 0;
            }
            cout << n + 2 << " ";
            cout << a << " " << b << " ";
            for(int i = 0; i < n; i++) {
                cout << i << " ";
            }
            cout << endl;
        }
    }
    return 0;
}
原文