题解:P13895 [蓝桥杯 2023 省 C] 异或和之差

· · 题解

\LARGE\text{前置知识:01 Trie}

Description

给定非负整数序列 A,求出两段非空不相交子段异或和的差的最大值。

Solution

为了保证子段不相交,我们可以枚举断点,让两段子段在断点两边。

那么如果我们能求出 pre_i 表示前 i 个点最大或最小异或和与 suf_i 表示后 i 个点最小或最大异或和,就可以直接枚举断点更新答案。

考虑怎么维护 pre_i。我们知道任意一段子段可以表示为两个前缀(异或和)的异或,那么只需要把前 i - 1 个前缀插入 01 Trie 中,贪心求出最大或最小值即可。

时间复杂度 O(n\log{n})。

代码实现细节较多。参考:

Code

#include <bits/stdc++.h>
#define fi first
#define se second
#define inf 1e9
using namespace std;
using ll = long long;
using db = double;
using pii = pair<int, int>;
constexpr int N = 2e5 + 5, M = 21, P = 1e9 + 7;
int n, a[N];
struct Trie {
    int trie[N * M][2], cnt;
    void insert(int x) {
        int p = 0;
        for (int i = 20; ~i; -- i) {
            bool t = (x >> i) & 1;
            if (!trie[p][t]) trie[p][t] = ++ cnt;
            p = trie[p][t];
        }
        return;
    }
    int max(int x) {
        int res = 0, p = 0;
        for (int i = 20; ~i; -- i) {
            bool t = (x >> i) & 1;
            if (trie[p][!t]) res |= 1 << i, p = trie[p][!t];
            else p = trie[p][t];
        }
        return res;
    }
    int min(int x) {
        int res = 0, p = 0;
        for (int i = 20; ~i; -- i) {
            bool t = (x >> i) & 1;
            if (trie[p][t]) p = trie[p][t];
            else res |= 1 << i, p = trie[p][!t];
        }
        return res;
    }
    void clear() {return memset(trie, 0, sizeof trie), cnt = 0, insert(0);}
} trie;
int pre[N], ans;
int main() {
    cin.tie(nullptr) -> sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; ++ i) cin >> a[i];
    trie.clear();
    for (int i = 1, sum = 0; i < n; ++ i) {
        pre[i] = max(pre[i - 1], trie.max(sum ^ a[i]));
        trie.insert(sum ^= a[i]);
    }
    trie.clear();
    for (int i = n, sum = 0; i > 1; -- i) {
        ans = max(ans, abs(pre[i - 1] - trie.min(sum ^ a[i])));
        trie.insert(sum ^= a[i]);
    }
    trie.clear();
    for (int i = 1, sum = 0; i < n; ++ i) {
        pre[i] = max(pre[i - 1], trie.min(sum ^ a[i]));
        trie.insert(sum ^= a[i]);
    }
    trie.clear();
    for (int i = n, sum = 0; i > 1; -- i) {
        ans = max(ans, abs(trie.max(sum ^ a[i]) - pre[i - 1]));
        trie.insert(sum ^= a[i]);
    }
    cout << ans << '\n';
    return 0;
}