其他分享
首页 > 其他分享> > cf242 E. XOR on Segment(线段树)

cf242 E. XOR on Segment(线段树)

作者:互联网

题意:

给定一个数组,要求两种操作:求区间和;让区间的每个数异或上x

思路:

每一位开一棵线段树,节点维护(某一位上的)1的数量。

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 100010, M = 25;
int n, m, w[N];

struct node {
    int l, r; int sum; bool tag; //是否取反
} tr[M][N*4];
void pushup(int t, int u)
{
    tr[t][u].sum = tr[t][u<<1].sum + tr[t][u<<1|1].sum;
}
void pushdown(int t, int u)
{
    node &root = tr[t][u], &left = tr[t][u<<1], &right = tr[t][u<<1|1];
    if(root.tag)
    {
        left.tag ^= 1, right.tag ^= 1;
        left.sum = left.r-left.l+1 - left.sum;
        right.sum = right.r-right.l+1 - right.sum;
        root.tag = 0;
    }
}
void build(int t, int u, int l, int r)
{
    if(l == r) tr[t][u] = {l, r, (w[l]>>t)&1};
    else
    {
        tr[t][u] = {l, r};
        int mid = l + r >> 1;
        build(t, u<<1, l, mid), build(t, u<<1|1, mid+1, r);
        pushup(t, u);
    }
}
void modify(int t, int u, int l, int r)
{
    if(tr[t][u].l >= l && tr[t][u].r <= r)
    {
        tr[t][u].tag ^= 1;
        tr[t][u].sum = tr[t][u].r-tr[t][u].l+1 - tr[t][u].sum;
    }
    else
    {
        pushdown(t, u);
        int mid = tr[t][u].l + tr[t][u].r >> 1;
        if(l <= mid) modify(t, u<<1, l, r);
        if(r > mid) modify(t, u<<1|1, l, r);
        pushup(t, u);
    }
}
int query(int t, int u, int l, int r)
{
    if(tr[t][u].l >= l && tr[t][u].r <= r) return tr[t][u].sum;
    pushdown(t, u);
    int mid = tr[t][u].l + tr[t][u].r >> 1, sum = 0;
    if(l <= mid) sum += query(t, u<<1, l, r);
    if(r > mid) sum += query(t, u<<1|1, l, r);
    return sum;
}

signed main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", &w[i]);

    for(int i = 0; i < M; i++) build(i, 1, 1, n);

    scanf("%d", &m); while(m--) {
        int op, l, r, x; scanf("%d%d%d", &op, &l, &r);
        if(op == 1) {
            long long res = 0;
            for(int i = 0; i < M; i++) res += query(i, 1, l, r) * (1ll<<i);
            printf("%lld\n", res);
        }
        else {
            scanf("%d", &x);
            for(int i = 0; i < M; i++) if((x>>i)&1) modify(i, 1, l, r);
        }
    }

    return 0;
}

标签:XOR,int,tr,sum,cf242,mid,long,modify,Segment
来源: https://www.cnblogs.com/wushansinger/p/15769017.html