模板
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn=1e5+5; 5 struct node 6 { 7 int l,r; 8 ll sum,lazy; 9 void update(ll x) 10 { 11 sum+=1ll*(r-l+1)*x; 12 lazy+=x; 13 } 14 }tree[maxn<<2]; 15 int n,a[maxn],q; 16 void push_up(int x) 17 { 18 tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum; 19 } 20 void push_down(int x) 21 { 22 int lazyval=tree[x].lazy; 23 if(lazyval) 24 { 25 tree[x<<1].update(lazyval); 26 tree[x<<1|1].update(lazyval); 27 tree[x].lazy=0; 28 } 29 } 30 void build(int x,int l,int r) 31 { 32 tree[x].l=l,tree[x].r=r; 33 tree[x].lazy=tree[x].sum=0; 34 if(l==r) 35 { 36 tree[x].sum=a[l]; 37 } 38 else 39 { 40 int mid=(l+r)>>1; 41 build(x<<1,l,mid); 42 build(x<<1|1,mid+1,r); 43 push_up(x); 44 } 45 } 46 void update(int x,int l,int r,ll val) 47 { 48 int L=tree[x].l,R=tree[x].r; 49 50 if(l<=L && R<=r) 51 { 52 tree[x].update(val); 53 } 54 else 55 { 56 push_down(x); 57 int mid=(L+R)>>1; 58 if(mid>=l)update(x<<1,l,r,val); 59 if(mid<r)update(x<<1|1,l,r,val); 60 push_up(x); 61 } 62 } 63 ll query(int x,int l,int r) 64 { 65 int L=tree[x].l,R=tree[x].r; 66 67 if(l<=L && R<=r) 68 { 69 return tree[x].sum; 70 } 71 else 72 { 73 push_down(x); 74 ll ans=0; 75 int mid=(L+R)>>1; 76 if(mid>=l)ans+=query(x<<1,l,r); 77 if(mid<r)ans+=query(x<<1|1,l,r); 78 push_up(x); 79 return ans; 80 } 81 82 } 83 int main() 84 { 85 scanf("%d%d",&n,&q); 86 for(int i=1;i<=n;i++) 87 scanf("%d",&a[i]); 88 build(1,1,n); 89 for(int i=1;i<=q;i++) 90 { 91 int l,r,op; 92 ll val; 93 scanf("%d",&op); 94 if(op==1) 95 { 96 scanf("%d%d%lld",&l,&r,&val); 97 update(1,l,r,val); 98 } 99 else 100 { 101 scanf("%d%d",&l,&r); 102 printf("%lld\n",query(1,l,r)); 103 } 104 105 106 } 107 return 0; 108 }