樹狀陣列的區間查詢與區間修改

weixin_30924079發表於2020-04-04

用c1存表示a[i]-a[i-1]的樹狀陣列
用c2存(i-1)*c1[i]

sum[x]=c1[1]+c1[1]+c1[2]+c1[1]+c1[2]+c1[3]+...+c1[1]+...+c1[x]
          =x*(c1[1]+c1[2]+c1[3]+…+c1[x])-(0*c1[1]+1*c1[2]+2*c1[3]+…+(x-1)*c1[x])
#include<iostream>
#include<cstdio>
using namespace std;

const long long MAXN=1e6+5;

long long c1[MAXN],c2[MAXN];
long long n,m;

long long lowbit(long long x){return x&(-x);}
void upd(long long f,long long t,long long w);
long long ask(long long p);

int main(){
    scanf("%d%d",&n,&m);
    for(long long i=1;i<=n;++i){
        long long t;
        cin>>t;
        upd(i,i,t);
    }
    for(long long i=1;i<=m;++i){
        char q;
        cin>>q;
        if(q=='Q'){
            long long t1,t2;
            cin>>t1>>t2;
            long long ans=ask(t2)-ask(t1-1);
            cout<<ans<<'\n';
        }
        else{
            long long t1,t2,t3;
            cin>>t1>>t2>>t3;
            upd(t1,t2,t3);
        }
    }
    return 0;
}

void upd(long long f,long long t,long long w){
    long long add1=(f-1)*w,add2=t*w;
    for(long long i=f;i<=n;i+=lowbit(i)){
        c1[i]+=w;
        c2[i]+=add1;
    }
    for(long long i=t+1;i<=n;i+=lowbit(i)){
        c1[i]-=w;
        c2[i]-=add2;
    }
}

long long ask(long long p){
    long long ans1=0,ans2=0;
    for(long long i=p;i>0;i-=lowbit(i)){
        ans1+=c1[i];
        ans2+=c2[i];
    }
    return p*ans1-ans2;
}

轉載於:https://www.cnblogs.com/buringstraw/p/9984328.html

相關文章