用c1存表示a[i]-a[i-1]的树状数组
用c2存(i-1)*c1[i]
1 2
| 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])
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #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; }
|