Luogu P3368 【模板】树状数组 2

gate

区间修改,单点查询

用差分维护。

因为查询返回了(1,x)的和,所以查询的时候直接查x就可以了。

至于修改,就要在区间开始加上,结尾减去,即(x,k),(y,-k)

代码如下

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
using namespace std;

const int maxn = 5e5+10;
int n,m,a[2],op,x,y,k;

struct BIT {
    long long c[maxn];
    int lowbit(int x) {
        return x & (-x);
    }
    void update(int x,long long k) {
        for(int i = x; i <= n; i += lowbit(i))
            c[i] += k;
    }
    long long query(int x) {
        long long ret = 0;
        for(int i = x; i; i -= lowbit(i))
            ret += c[i];
        return ret;
    }
} t;

int main() {
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++) {
        scanf("%d",&a[i%2]);
        t.update(i,a[i%2] - a[(i-1)%2]);
    }
    for(int i = 1; i <= m; i++) {
        scanf("%d%d",&op,&x);
        if(op == 1) {
            scanf("%d%d",&y,&k);
            t.update(x,k);
            t.update(y+1,-k);
        }
        if(op == 2)
            printf("%lld\n",t.query(x));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/mogeko/p/11837764.html