线段树区间求和模板(区间修改)

xiaoxiao2021-02-28  82

#include <stdio.h> #include <iostream> #include <algorithm> #include <math.h> #include <cstring> #include <queue> #include <map> #include <vector> #include <string> #define mem(a) memset(a,0,sizeof(a)) #define mem2(a) memset(a,-1,sizeof(a)) #define mod 1000000007 #define mx 100005 using namespace std; long long a[mx],sum[mx<<2],add[mx<<2];//直接开long long 就好了。sum和add数组要开数据量的四倍别忘了。 int n,l; void pushup (int x)//维护当前线段的区间和。 { sum[x]=sum[x<<1]+sum[x<<1|1]; } void build (int l,int r,int x)//建树 { if(l==r) { sum[x]=a[l]; return; } int mid = (l+r)/2; build(l,mid,x<<1); build(mid+1,r,x<<1|1); pushup(x); } void pushdown (int x,int lx,int rx)//下推懒惰标记。 { //lx,rx分别是左子树,右子树的数量。 if(add[x]) { //下推标记 add[x<<1]+=add[x]; add[x<<1|1]+=add[x]; //修改子节点的sum使之与对应的add相对应。 sum[x<<1]+=add[x]*lx; sum[x<<1|1]+=add[x]*rx; //清除该节点的懒惰标记。 add[x]=0; } } void update (int L,int R,int C,int l,int r,int x) { if(L<=l&&r<=R) { sum[x]+=C*(r-l+1); add[x]+=C; return ; } int mid=(l+r)/2; pushdown(x,mid-l+1,r-mid); //一定要在向下更新操作进行之前下推懒惰标记。 if(L<=mid) update(L,R,C,l,mid,x<<1); if(R>mid) update(L,R,C,mid+1,r,x<<1|1); pushup(x); } long long query (int L,int R,int l,int r,int x)//返回值一定要写long long 别问我怎么知道的。 { if(L<=l&&r<=R) { return sum[x]; } int mid = (l+r)>>1; pushdown(x,mid-l+1,r-mid); //下推懒惰标记,更新左子树和右子树维护的线段的区间和的值。 long long ans=0; if(L<=mid) ans+=query(L,R,l,mid,x<<1); if(R>mid ) ans+=query(L,R,mid+1,r,x<<1|1); return ans; } int main() { #ifndef ONLINE_JUDGE freopen("1.txt","r",stdin); #endif // ONLINE_JUDGE ios_base::sync_with_stdio(false); cin.tie(0); char c; int x,y,z; while(cin>>n>>l) { mem(sum); mem(add); mem(a); for(int i=1; i<=n; ++i) cin>>a[i]; build(1,n,1); while(l--) { cin>>c; if(c=='Q') { cin>>x>>y; cout<<query(x,y,1,n,1)<<endl; } if(c=='C') { cin>>x>>y>>z; update(x,y,z,1,n,1); } } } return 0; }
转载请注明原文地址: https://www.6miu.com/read-19034.html

最新回复(0)