1 条题解

  • 0
    @ 2026-11-2 15:26:41

    区间异或和(Subarray Maximum XOR) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        if (!(cin >> n)) return 0;
        vector<int> a(n + 1);
        for (int i = 1; i <= n; ++i) cin >> a[i];
        int max_nodes = (n + 2) * 31;
        vector<int> ch0(max_nodes, 0), ch1(max_nodes, 0);
        int tot = 1;
        auto clear_trie = [&]() {
            for (int i = 1; i <= tot; ++i) {
                ch0[i] = ch1[i] = 0;
            }
            tot = 1;
        };
        auto insert = [&](int x) {
            int u = 1;
            for (int b = 29; b >= 0; --b) {
                int bit = (x >> b) & 1;
                if (bit == 0) {
                    if (!ch0[u]) ch0[u] = ++tot;
                    u = ch0[u];
                } else {
                    if (!ch1[u]) ch1[u] = ++tot;
                    u = ch1[u];
                }
            }
        };
        auto query = [&](int x) {
            int u = 1, res = 0;
            for (int b = 29; b >= 0; --b) {
                int bit = (x >> b) & 1;
                if (bit == 0) {
                    if (ch1[u]) {
                        res |= (1 << b);
                        u = ch1[u];
                    } else {
                        u = ch0[u];
                    }
                } else {
                    if (ch0[u]) {
                        res |= (1 << b);
                        u = ch0[u];
                    } else {
                        u = ch1[u];
                    }
                }
            }
            return res;
        };
        vector<int> L(n + 1, 0), R(n + 2, 0);
        insert(0);
        int pref = 0;
        for (int i = 1; i <= n; ++i) {
            pref ^= a[i];
            L[i] = max(L[i - 1], query(pref));
            insert(pref);
        }
        clear_trie();
        insert(0);
        int suff = 0;
        for (int i = n; i >= 1; --i) {
            suff ^= a[i];
            R[i] = max(R[i + 1], query(suff));
            insert(suff);
        }
        long long ans = 0;
        for (int i = 1; i < n; ++i) {
            ans = max(ans, (long long)L[i] + R[i + 1]);
        }
        cout << ans << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8831
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者