Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Xor Sigma Problem

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> &a) {
    int n = a.size();

    long long ans = 0;
    for (int b = 0; b < 30; b++) {
        // cnt[i][j] is the number of subarrays ending at i with xor j.
        vector<vector<long long>> cnt(n, vector<long long>(2, 0));

        for (int i = 0; i < n; i++) {
            int now = (a[i] >> b) & 1;

            // Take this element alone.
            cnt[i][now] = 1;

            // Merge it with previous element's subarray.
            for (int j = 0; j < 2; j++) {
                if (i) {
                    int w = now ^ j;
                    cnt[i][j] += cnt[i - 1][w];
                }
            }
        }
        for (int i = 0; i < n; i++) {
            ans += (1LL << b) * cnt[i][1];
        }
    }

    // Remove subarrays of length 1.
    cout << ans - accumulate(a.begin(), a.end(), 0LL) << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    solve(a);
}