线段树模板
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 #define maxn 100005 6 7 using namespace std; 8 9 typedef long long ll; 10 ll tree[maxn<<2],num[maxn],lazytag[maxn<<2]; 11 int n,m; 12 ll ans; 13 14 inline void build(int k,int l,int r) 15 { 16 if(l==r) 17 { 18 tree[k]=num[l]; 19 return; 20 } 21 int mid=(l+r)>>1,son=k<<1; 22 build(son,l,mid); build(son|1,mid+1,r); 23 tree[k]=tree[son]+tree[son|1]; 24 return; 25 } 26 27 inline void pushdown(int k,int l,int r) 28 { 29 int mid=(l+r)>>1,son=k<<1; 30 tree[son]+=(mid-l+1)*lazytag[k]; lazytag[son]+=lazytag[k]; 31 tree[son|1]+=(r-mid)*lazytag[k]; lazytag[son|1]+=lazytag[k]; 32 lazytag[k]=0; 33 return; 34 } 35 36 inline void getsum(int k,int l,int r,int x,int y) 37 { 38 if(x>r||y<l) return; 39 if(x<=l&&r<=y) 40 { 41 ans+=tree[k]; 42 return; 43 } 44 if(lazytag[k]) pushdown(k,l,r); 45 int mid=(l+r)>>1,son=k<<1; 46 getsum(son,l,mid,x,y); getsum(son|1,mid+1,r,x,y); 47 tree[k]=tree[son]+tree[son|1]; 48 return; 49 } 50 51 inline void update(int k,int l,int r,int x,int y,ll v) 52 { 53 if(x>r||y<l) return; 54 if(x<=l&&r<=y) 55 { 56 tree[k]+=(r-l+1)*v; 57 lazytag[k]+=v; 58 return; 59 } 60 if(lazytag[k]) pushdown(k,l,r); 61 int mid=(l+r)>>1,son=k<<1; 62 update(son,l,mid,x,y,v); update(son|1,mid+1,r,x,y,v); 63 tree[k]=tree[son]+tree[son|1]; 64 return; 65 } 66 67 int main() 68 { 69 scanf("%d%d",&n,&m); 70 for(int i=1;i<=n;i++) 71 scanf("%d",&num[i]); 72 build(1,1,n); 73 for(int i=1;i<=m;i++) 74 { 75 int q; 76 scanf("%d",&q); 77 if(q==1) 78 { 79 int x,y; ll v; 80 scanf("%d%d%lld",&x,&y,&v); 81 update(1,1,n,x,y,v); 82 } 83 if(q==2) 84 { 85 int x,y; 86 scanf("%d%d",&x,&y); 87 ans=0; 88 getsum(1,1,n,x,y); 89 printf("%lld\n",ans); 90 } 91 } 92 return 0; 93 }