树状数组之区间修改,查询

时间:2022-09-03 10:27:52

学习:https://www.cnblogs.com/lcf-2000/p/5866170.html

题目:http://codevs.cn/problem/1082/

树状数组之区间修改,查询树状数组之区间修改,查询
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int M=1e6+5;
ll cnt1[M],cnt2[M];
int n;
int lowbit(int x){
    return x&(-x);
}
void add(int x,int y){////给差分数组中的位置x加上y
    for(int i=x;i<=n;i+=lowbit(i)){
        cnt1[i]+=1ll*y,cnt2[i]+=(ll)x*y;
    }

}
ll sum(int x){
    ll ans=0;
    for(int i=x;i>0;i-=lowbit(i))
        ans+=(x+1)*1ll*cnt1[i]-cnt2[i];
    return ans;
}
int main(){

    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int t;
        scanf("%d",&t);
        add(i,t);
        add(i+1,-t);
    }
    int m;
    scanf("%d",&m);
    while(m--){
        int op;
        scanf("%d",&op);
        if(op==1){
            int l,r,c;
            scanf("%d%d%d",&l,&r,&c);
            add(l,c);
            add(r+1,-c);
        }
        else{
            int l,r;
            scanf("%d%d",&l,&r);
            printf("%lld\n",sum(r)-sum(l-1));
        }
    }
    return 0;
}
View Code