codeforces242E. XOR on Segment(线段树)

题目链接:codeforces242E. XOR on Segment

题意:

给定一个序列,然后有两种操作:

  1. 区间求和。
  2. 区间每个数异或x。

题解:

把每个数写成二进制形式,然后按二进制位建线段树,即建20棵线段树。然后对于每棵线段树维护区间和,以及区间异或。因为拆分之后,每一位只有可能是0或1,所以可以直接维护区间翻转即可。

参考代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e5 + 10;
int n, m;
int a[MAXN];
int seg[MAXN << 2][25], lazy[MAXN << 2][25];
void pushup(int rt)
{
    for (int i = 0; i <= 20; i++)
        seg[rt][i] = seg[rt << 1][i] + seg[rt << 1 | 1][i];
}
void pushdown(int l, int r, int rt)
{
    for (int i = 0; i <= 20; i++)
        if (lazy[rt][i])
        {
            lazy[rt << 1][i] ^= lazy[rt][i];
            lazy[rt << 1 | 1][i] ^= lazy[rt][i];
            int mid = (l + r) >> 1;
            seg[rt << 1][i] = (mid - l + 1) - seg[rt << 1][i];
            seg[rt << 1 | 1][i] = (r - mid) - seg[rt << 1 | 1][i];
            lazy[rt][i] = 0;
        }
}
void build(int l, int r, int rt)
{
    if (l == r)
    {
        for (int i = 0; i <= 20; i++)
        {
            seg[rt][i] = (a[l] >> i) & 1;
            lazy[rt][i] = 0;
        }
        return;
    }
    int mid = (l + r) >> 1;
    build(l, mid, rt << 1);
    build(mid + 1, r, rt << 1 | 1);
    pushup(rt);
}
void update(int L, int R, int pos, int l, int r, int rt)
{
    if (L <= l && r <= R)
    {
        lazy[rt][pos] ^= 1;
        seg[rt][pos] = (r - l + 1) - seg[rt][pos];
        return;
    }
    pushdown(l, r, rt);
    int mid = (l + r) >> 1;
    if (L <= mid)
        update(L, R, pos, l, mid, rt << 1);
    if (R > mid)
        update(L, R, pos, mid + 1, r, rt << 1 | 1);
    pushup(rt);
}
ll query(int L, int R, int pos, int l, int r, int rt)
{
    if (L <= l && r <= R)
        return seg[rt][pos];
    pushdown(l, r, rt);
    int mid = (l + r) >> 1;
    ll res = 0;
    if (L <= mid)
        res += query(L, R, pos, l, mid, rt << 1);
    if (R > mid)
        res += query(L, R, pos, mid + 1, r, rt << 1 | 1);
    return res;
}
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    build(1, n, 1);
    scanf("%d", &m);
    while (m--)
    {
        int op, l, r;
        scanf("%d%d%d", &op, &l, &r);
        if (op == 1)
        {
            ll ans = 0;
            for (int i = 0; i <= 20; i++)
                ans += query(l, r, i, 1, n, 1) * (1ll << i);
            printf("%lld\n", ans);
        }
        else
        {
            int x;
            scanf("%d", &x);
            for (int i = 0; i <= 20; i++)
                if ((x >> i) & 1)
                    update(l, r, i, 1, n, 1); 
        }
    }
    return 0;
}

发表留言

人生在世,错别字在所难免,无需纠正。