AcWing 242. 一个简单的整数问题(树状数组的区间增加与单点查询操作)

树状数组的基本用途就是维护序列的前缀和, 仅支持"单点增加"和"区间查询"操作(代码如下)

//单点增加
void add(int x, int y){
    for (; x <= N; x += x & -x)
        c[x] += y;
}
//区间查询
int ask(int x){
    int ans = 0;
    for (; x; x -= x & -x)
        ans += c[x];
    return ans;
}

我们可以构造a序列的差分来实现"区间增加".

我们新建一个b数组,起初为全0.对于指令"C l r d",我们转化成以下的操作:

1.把b[l]加上d

2.把b[r + 1]减去d

然后用树状数组来维护b序列的前缀和,可以发现b[1~x]就是对a[x]的累计增加的大小.对于"Q x"指令,我们查询b[1~x],再加上原本的a[x]即可.

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m;
int a[100010], b[100010];
void add(int x, int y){
    for (; x <= n; x += x & -x)
        b[x] += y;
}

int ask(int x){
    int ans = 0;
    for (; x; x -= x & -x)
        ans += b[x];
    return ans;
}

signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) 
        cin >> a[i];
    while (m--){
        string op;
        cin >> op;
        if (op == "C"){
            int l, r, d;
            cin >> l >> r >> d;
            add(l, d), add(r + 1, -d);
        }
        else if (op == "Q"){
            int x;
            cin >> x;
            cout << ask(x) + a[x] << '\n';
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值