Merge_all @ 2024-05-28 18:06:57
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=200010;
int n,m;
int a[N],tree[N<<2],tag[N];
int ls(int p){return p<<1;}
int rs(int p){return p<<1|1;}
void push_up(int p){
tree[p]=tree[ls(p)]+tree[rs(p)];
}
void build(int p,int pl,int pr){
tag[p]=0;
if(pl==pr){tree[p]=a[pl];return ;}
int mid=(pl+pr)>>1;
build(ls(p),pl,mid),build(rs(p),mid+1,pr);
push_up(p);
}
void addtag(int p,int pl,int pr,int d){
tag[p]+=d;
tree[p]+=(pr-pl+1)*d;
}
void push_down(int p,int pl,int pr){
if(tag[p]){
int mid=pl+pr>>1;
addtag(ls(p),pl,mid,tag[p]),addtag(rs(p),mid+1,pr,tag[p]);
tag[p]=0;
}
}
void update(int L,int R,int p,int pl,int pr,int d){
// cout<<"Gina Smith\n";
if(L<=pl&&R>=pr){
addtag(p,pl,pr,d);
return ;
}
// cout<<"Gina Smith\n";
push_down(p,pl,pr);
int mid=pl+pr>>1;
if(L<=mid) update(L,R,ls(p),pl,mid,d);
if(R>mid) update(L,R,rs(p),mid+1,pr,d);
push_up(p);
// cout<<"Gina Smith\n";
}
int query(int L,int R,int p,int pl,int pr){
if(L<=pl&&R>=pr){
return tree[p];
}
push_down(p,pl,pr);
int res=0;
int mid=pl+pr>>1;
if(L<=mid) res+=query(L,R,ls(p),pl,mid);
if(R>mid) res+=query(L,R,rs(p),mid+1,pr);
return res;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
build(1,1,n);
// cout<<"Gina Smith\n";
while(m--){
int opt,x,y,z;
cin>>opt;
if(opt==1){
cin>>x>>y>>z;
update(x,y,1,1,n,z);
}
else{
cin>>x>>y;
cout<<query(x,y,1,1,n)<<"\n";
}
}
return 0;
}
不知道哪里错了。
by qazsedcrfvgyhnujijn @ 2024-05-28 18:14:14
tag
数组也要开
建议写成结构体:
struct Node {
long long sum, tag;
} t[N << 2];
不容易写错
by masiyudr @ 2024-05-28 19:10:44
%%%
by masiyudr @ 2024-05-28 19:11:32
@chenhaoyu_ACAC 你居然会线段树!!!%%%
by Merge_all @ 2024-05-28 20:31:24
@hhy517090 好的,谢谢。
by Merge_all @ 2024-05-28 20:32:32
@hhy517090 AC了,感激!必须互关一波。