题解:P17204 「DLESS-6」XOR and MEX

· · 题解

P17204 「DLESS-6」XOR and MEX 题解

思路

这题其实不难。

看了一眼样例,大胆猜测答案就是原数组中第一个没有出现的非负整数。

那接下来我们需要证明这样是对的。

注意到,如果 f(a, x) = y,那说明 x \oplus y 在原数组中并没有出现,所以有 f(a, x \oplus y) = 0,整理一下,得到这两条式子。

  1. x + f(a, x) = x + y
  2. x \oplus y + f(a, x \oplus y) = x \oplus y

很明显的,有 x \oplus y < x + y,此时答案只会选满足 f(a, x) = 0x

没错,那最后要我们求的答案其实就是原数组中没有出现过的最小的非负整数。

时间复杂度: O(T \times n)

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 1e6 + 5;
ll a[N];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll T;
    cin >> T;
    while(T--) {
        ll n;
        cin >> n;
        for(ll i = 1; i <= n; i++) cin >> a[i];
        sort(a + 1, a + n + 1);
        ll ans = -1;
        if(a[1] > 0) {
            cout << 0 << endl;
            continue;
        }
        for(ll i = 1; i < n; i++) {
            if(a[i + 1] - a[i] > 1) {
                ans = a[i] + 1;
                break;
            }
        }
        if(ans == -1) ans = a[n] + 1;
        cout << ans << endl;
    }
    return 0;
}

后记

求管理员通过,管理员辛苦了。

如果这篇题解对你有帮助,不妨点个赞再走吧。