[POJ 2368 A Simple Problem with Integers] 树状数组区间修改、区间查询

[POJ 2368 A Simple Problem with Integers] 树状数组区间修改、区间查询

知识点:data structure binary index tree

1. 题目链接

[POJ 2368 A Simple Problem with Integers]

2. 题意描述

对数组 an 进行 q 次区间修改(加上一个数),区间查询。
1n,q105,109Ai109

3. 解题思路

这个用线段树做也就是一个无脑题。之前这类区间查询的还真的很少用树状数组做。
原理:原数组为 ai ,差分数组为 di=aiai1 ;则 an=ni=1di ;
所以,

i=1nai=i=1nj=1idj=i=1n[(ni+1)di]=(x+1)i=1ndii=1n(dii)

通过维护差分数组 di ,以及 dii 。就可以维护原数组的前缀和。进而维护出原数组的区间和。

4. 实现代码

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
const int MAXN = 100000 + 5;

int n, q;

template<class T>
struct BIT {
    T C[MAXN];
    void I() { memset(C, 0, sizeof(C)); }
    inline T lowbit(T x) { return x & (-x); }
    void update(int x, LL val) {
        while(x < MAXN) { C[x] += val; x += lowbit(x); }
    }
    T query(int x) {
        T ret = 0;
        while(x > 0) { ret += C[x]; x -= lowbit(x); }
        return ret;
    }
};
BIT<LL> a, b;
void update(int x, LL v) { a.update(x, v); b.update(x, v * x); }
void update(int l, int r, LL v) { update(l, v); update(r + 1, -v); }
LL presum(int x) { return (LL)(x + 1) * a.query(x) - b.query(x); }
LL query(int l, int r) { return presum(r) - presum(l - 1); }

int main() {
#ifdef ___LOCAL_WONZY___
    freopen("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
    char op[5];
    LL l, r, v;
    while(~scanf("%d %d", &n, &q)) {
        a.I(); b.I();
        vector<LL> A(n + 1);
        A[0] = 0;
        for(int i = 1; i <= n; i++) {
            scanf("%lld", &A[i]);
            update(i, A[i] - A[i - 1]); /// 注意这里
        }
        while(q --) {
            scanf("%s %lld %lld", op, &l, &r);
            if(op[0] == 'Q') {
                printf("%lld\n", query(l, r));
            } else {
                scanf("%lld", &v);
                update(l, r, v);
            }
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值