1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 Long Longa[2000003],sum[10000003],add[10000003],n;6 voidPushup (Long LongRT) {sum[rt]=sum[rt<<1]+sum[rt<<1|1];}7 voidBuildLong LongLLong LongRLong LongRT)8 {9 if(L==R) {Sum[rt]=a[l];return;}Ten Long LongMid= (l+r) >>1; OneBuild (l,mid,rt<<1); ABuild (mid+1,r,rt<<1|1); - pushup (RT); - } the voidPushdown (Long LongRtLong LonglnLong LongRN) - { - if(Add[rt]) - { +add[rt<<1]+=Add[rt]; -add[rt<<1|1]+=Add[rt]; +sum[rt<<1]+=add[rt]*Ln; Asum[rt<<1|1]+=add[rt]*RN; atadd[rt]=0; - } - } - voidUpdata (Long LongLLong LongRLong LongCLong LongLLong LongRLong LongRT) - { - if((l<=l) && (r<=R)) in { -sum[rt]+=c* (r-l+1); toAdd[rt]+=c;return; + } - Long LongMid= (l+r) >>1; thePushdown (rt,mid-l+1, R-mid); * if(L<=mid) Updata (l,r,c,l,mid,rt<<1); $ if(R>mid) Updata (l,r,c,mid+1,r,rt<<1|1);Panax Notoginseng pushup (RT); - } the Long LongQueryLong LongLLong LongRLong LongLLong LongRLong LongRT) + { A if((l<=l) && (r<=r))returnSum[rt]; the Long LongMid= (l+r) >>1; +Pushdown (rt,mid-l+1, R-mid); - Long Longans=0; $ if(L<=mid) Ans+=query (l,r,l,mid,rt<<1); $ if(R>mid) Ans+=query (l,r,mid+1,r,rt<<1|1); - returnans; - } the intMain () - {Wuyiscanf"%lld",&n); the Long Longi,j,q,t,l,r,x; - for(i=1; i<=n;++i) scanf ("%lld",&a[i]); WuBuild1N1); -scanf"%lld",&q); About for(i=1; i<=q;++i) $ { -scanf"%lld",&t); - if(t==1) - { Ascanf"%lld%lld%lld",&l,&r,&x); +Updata (L,r,x,1N1); the } - Else $ { thescanf"%lld%lld",&l,&R); theprintf"%lld\n", Query (L,r,1N1)); the } the } - return 0; in}
Codevs 1082 Segment Tree Exercises 3 Template questions