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 : Sum of XOR Functions

#include <atcoder/modint>
#include <bits/stdc++.h>

using namespace std;
using namespace atcoder;

using mint = modint998244353;

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

    mint ans = 0;
    for (int b = 0; b < 30; b++) {
        vector<vector<mint>> dp(n, vector<mint>(2, 0));
        vector<vector<mint>> cnt(n, vector<mint>(2, 0));

        // cnt[i][j] is the number of subarrays ending at i with xor j.
        // dp[i][j] is the sum of length of all subarrays ending at i with
        // xor j.

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

            // Take this element alone.
            cnt[i][now] = 1;
            dp[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];
                    dp[i][j] += dp[i - 1][w] + cnt[i - 1][w];
                }
            }
        }
        for (int i = 0; i < n; i++) {
            ans += (1LL << b) * dp[i][1];
        }
    }
    cout << ans.val() << "\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);
}