Segment Tree

时间:2023-03-09 06:26:15
Segment Tree

姑且叫这种数据结构这个名字

#include<iostream>
#include<cstdio>
#define N 200005
#define Lson ret<<1
#define Rson ret<<1|1
#define lson l,mid,ret<<1
#define rson mid+1,r,ret<<1|1
using namespace std; typedef long long ll; int n,m,x,y; struct node{
int l,r;
ll w,f;
}t[N<<2]; inline ll Merge(int LS,int RS){
return t[LS].w+t[RS].w;
} inline void Build(int l,int r,int ret){
t[ret].l=l;t[ret].r=r;
if(l==r){
scanf("%lld",&t[ret].w);
return;
}
int mid=(l+r)>>1;
Build(lson);
Build(rson);
t[ret].w=Merge(Lson,Rson);
}
inline void Pushdown(int ret){
t[Lson].f+=t[ret].f;
t[Rson].f+=t[ret].f;
t[Lson].w+=(ll)t[ret].f*(t[Lson].r-t[Lson].l+1);
t[Rson].w+=(ll)t[ret].f*(t[Rson].r-t[Rson].l+1);
t[ret].f=0;
} inline ll Quary(int l,int r,int ret,int L,int R){
ll ans=0;
if(t[ret].f)Pushdown(ret);
if(t[ret].l>=L&&t[ret].r<=R)
return t[ret].w;
int mid=(l+r)>>1;
if(L<=mid)ans+=Quary(lson,L,R);
if(R>=mid+1)ans+=Quary(rson,L,R);
return ans;
} inline void Update(int l,int r,int ret,int Ch,int L,int R){
if(l>=L&&r<=R){
t[ret].f+=Ch;
t[ret].w+=(ll)(r-l+1)*Ch;
return ;
}
if(t[ret].f)Pushdown(ret);
int mid=(l+r)>>1;
if(L<=mid)Update(lson,Ch,L,R);
if(R>=mid+1)Update(rson,Ch,L,R);
t[ret].w=Merge(Lson,Rson);
} int main(){
scanf("%d%d",&n,&m);
Build(1,n,1);
int opt,a,b;ll c;
while(m--){
scanf("%d%d%d",&opt,&a,&b);
if(opt==1){
scanf("%d",&c);
Update(1,n,1,c,a,b);
}
else printf("%lld\n",Quary(1,n,1,a,b));
}
return 0;
}