__QingYu @ 2022-10-24 22:41:57
悬赏关注一个
#include<iostream>
using namespace std;
typedef long long ll;
const int maxn=1e6;
struct node{
ll sum;
ll tag;
}tree[maxn<<2];
ll arr[maxn+5];
void pushUp(ll root){
tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
return ;
}
void pushDown(ll root,ll ln,ll rn){
if(tree[root].tag){//Has tag
tree[root<<1].tag+=tree[root].tag;
tree[root<<1|1].tag+=tree[root|1].tag;
tree[root<<1].sum+=ln*tree[root].tag;
tree[root<<1|1].sum+=rn*tree[root].tag;
tree[root].tag=0;
}
return ;
}
void build(ll l,ll r,ll root){
if(l==r){
tree[root].sum=arr[l];
return ;
}
ll mid=(l+r)>>1;
build(l,mid,root<<1);
build(mid+1,r,root<<1|1);
pushUp(root);
return ;
}
void updateQ(ll l,ll r,ll L,ll R,ll v,ll root){//区间更新
if(L<=l && r<=R){
tree[root].sum+=(r-l+1)*v;
tree[root].tag+=v;//Lazy tag
return ;
}
ll mid=(l+r)>>1;
ll ln=mid-l+1,rn=r-mid;
pushDown(root,ln,rn);
if(L<=mid){
updateQ(l,mid,L,R,v,root<<1);
}
if(R>mid){
updateQ(mid+1,r,L,R,v,root<<1|1);
}
pushUp(root);//update
return ;
}
ll query(int l,int r,int L,int R,int root){
ll sum=0;
if(L<=l && r<=R){
return tree[root].sum;
}
ll mid=(l+r)>>1;
ll ln=mid-l+1;
ll rn=r-mid;
pushDown(root,ln,rn);
if(L<=mid){
sum+=query(l,mid,L,R,root>>1);
}
if(mid<R){
sum+=query(mid+1,r,L,R,root>>1|1);
}
return sum;
}
int main(){
ll n,m;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>arr[i];
}
build(1,n,1);
int t=0,l,r,v;
while(m--){
cin>>t;
if(t==1){
cin>>l>>r>>v;
updateQ(1,n,l,r,v,1);
}else{
cin>>l>>r;
cout<<query(1,n,l,r,1)<<endl;
}
}
}
by 8atemak1r @ 2022-10-24 22:46:08
@__QingYu pushdown 的 if 里面第二行
by hhw_khw @ 2022-10-24 22:50:27
tree[root<<1|1].tag+=tree[root|1].tag;
by Fimlty @ 2022-10-24 22:57:16
tree[root<<1|1].tag+=tree[root|1].tag;应该为tree[root<<1|1].tag+=tree[root].tag;
by __QingYu @ 2022-10-25 20:19:50
@8atemak1r @hhw_khw @Fimlty
谢谢,已解决,此贴解决