#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
#include<cmath>
#include<vector>
#define ll long long
using namespace std;
int a[100010];
struct node{
int l,r;
ll sum,lazy;
}t[400040];
int n,m;
void spread(int p){
if(t[p].lazy==0)
return;
t[p*2].sum+=t[p].lazy*(t[p*2].r-t[p*2].l+1);
t[p*2+1].sum+=t[p].lazy*(t[p*2+1].r-t[p*2+1].l+1);
t[p*2].lazy+=t[p].lazy;
t[p*2+1].lazy+=t[p].lazy;
t[p].lazy=0;
}
void build(int p,int l,int r){
t[p].l=l;
t[p].r=r;
t[p].lazy=0;
if(l==r){
t[p].sum=a[l];
return;
}
int mid=(l+r)>>1;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
t[p].sum=t[p*2].sum+t[p*2+1].sum;
}
void add(int p,int l,int r,int k){
if(t[p].l>=l&&t[p].r<=r){
t[p].sum+=(t[p].r-t[p].l+1)*(ll)k;
t[p].lazy+=k;
return;
}
spread(p);
int mid=(t[p].l+t[p].r)>>1;
if(mid>=l)add(p*2,l,r,k);
if(mid+1<=r)add(p*2+1,l,r,k);
t[p].sum=t[p*2].sum+t[p*2+1].sum;
}
ll ask(int p,int l,int r){
if(t[p].l>=l&&t[p].r<=r){
return t[p].sum;
}
spread(p);
int mid=t[p].l+t[p].r>>1;
ll ans=0;
if(mid>=l)ans+=ask(p*2,l,r);
if(mid+1<=r)ans+=ask(p*2+1,l,r);
return ans;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
while(m--){
int t;
cin>>t;
if(t==1){
int x,y,k;
scanf("%d%d%d",&x,&y,&k);
add(1,x,y,k);
}
if(t==2){
int x,y;
scanf("%d%d",&x,&y);
cout<<ask(1,x,y)<<endl;
}
}
return 0;
}
洛谷 P3372 【模板】线段树 1 待补充
最新推荐文章于 2024-09-16 18:31:59 发布