CF202E XOR on Segment (线段树 拆位)

题目链接: XOR on Segment

大致题意

有一个长度为n的序列, 有两种操作.
​ ①给定l r 你需要返回[l, r]的区间和
​ ②给定l r c 需要给[l, r]区间的每一个数字⊕c.

解题思路

线段树 这题一看就在考DS

考虑到区间修改, 由于⊕操作不像区间加和等操作, 不可以直接传递. 因此我们考虑拆位来计算.

线段树内部维护当前区间内所有数字每一个二进制位上1的个数. 这样如果我们要给一个区间异或上一个数字, 那么对于这个数字二进制位为1的位置而言, 区间内所有数字的这一位01会互换. 假设本身这一位在这个区间中有num个, 区间总数字个数为len, 则每次变化为: num = len - num.

当我们需要区间求和时, 我们同样得到每一位的个数, 然后扩大对应的倍数即可.

AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E5 + 10, B = 20;
int w[N];
struct node {
    int l, r;
    int cou[20]; //1的个数
    int flag;
}t[N << 2];
void pushdown(node& op, int flag) {
    int len = op.r - op.l + 1;
    for (int i = 0; i < B; ++i) if (flag >> i & 1) op.cou[i] = len - op.cou[i];
    op.flag ^= flag;
}
void pushdown(int x) {
    if (!t[x].flag) return;
    pushdown(t[x << 1], t[x].flag), pushdown(t[x << 1 | 1], t[x].flag);
    t[x].flag = 0;
}
void pushup(int x) {
    for (int i = 0; i < B; ++i) {
        t[x].cou[i] = t[x << 1].cou[i] + t[x << 1 | 1].cou[i];
    }
}
void build(int l, int r, int x = 1) {
    t[x] = { l, r };
    if (l == r) {
        for (int i = 0; i < B; ++i) t[x].cou[i] = w[l] >> i & 1;
        return;
    }
    int mid = l + r >> 1;
    build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
    pushup(x);
}

void modify(int l, int r, int c, int x = 1) {
    if (l <= t[x].l and r >= t[x].r) {
        pushdown(t[x], c);
        return;
    }
    pushdown(x);
    int mid = t[x].l + t[x].r >> 1;
    if (l <= mid) modify(l, r, c, x << 1);
    if (r > mid) modify(l, r, c, x << 1 | 1);
    pushup(x);
}
ll ask(int l, int r, int x = 1) {
    if (l <= t[x].l and r >= t[x].r) {
        ll res = 0;
        for (int i = 0; i < B; ++i) res += (1ll << i) * t[x].cou[i];
        return res;
    }
    pushdown(x);
    int mid = t[x].l + t[x].r >> 1;
    ll res = 0;
    if (l <= mid) res = ask(l, r, x << 1);
    if (r > mid) res += ask(l, r, x << 1 | 1);
    return res;
}

int main()
{
    int n; cin >> n;
    rep(i, n) scanf("%d", &w[i]);
    build(1, n);

    int m; cin >> m;
    rep(i, m) {
        int tp, l, r; scanf("%d %d %d", &tp, &l, &r);
        if (tp == 1) printf("%lld\n", ask(l, r));
        else {
            int c; scanf("%d", &c);
            modify(l, r, c);
        }
    }
    return 0;
}

END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥Fau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值