区间修改不对,求调,要注释看上篇
查看原帖
区间修改不对,求调,要注释看上篇
1349423
jms23002楼主2025/1/18 20:03
#include<bits/stdc++.h>
using namespace std;
const long long N=1e5+5;
long long n,m,a[N];
struct node{
	long long l;
	long long r;
	long long sum;
	long long lazy;
}tr[4*N];
void pushup(long long u){
	tr[u].sum=tr[u*2].sum+tr[u*2+1].sum;
}
void pushdown(long long u){
	if(tr[u].lazy){
		tr[u*2].lazy+=tr[u].lazy; 
		tr[u*2].sum+=(tr[u*2].r-tr[u*2].l+1)*tr[u].lazy;
		
		tr[u*2+1].lazy+=tr[u].lazy;
		tr[u*2+1].sum+=(tr[u*2+1].r-tr[u*2+1].l+1)*tr[u].lazy;
		 
		tr[u].lazy=0;
	}
}
void build(long long u,long long l,long long r){
	tr[u].l=l;
	tr[u].r=r;
	if(tr[u].l==tr[u].r){
	    tr[u].sum=a[l];
	    tr[u].lazy=0;
	    return;
	}
	long long mid=(tr[u].l+tr[u].r)/2;
	build(u*2,l,mid);build(u*2+1,mid+1,r);
	pushup(u);
}
void mofity(long long u,long long l,long long r,long long v){
	if(l<=tr[u].l&&tr[u].r<=r){
		tr[u].lazy+=v;
		tr[u].sum+=(tr[u].r-tr[u].l+1)*v;
		return;
	} 
	pushdown(u);
	long long mid=(tr[u].r+tr[u].l)/2;
	if(l<=mid){
		mofity(u*2,l,r,v);
	} 
	else if(mid<r){
		mofity(u*2+1,l,r,v);
	} 
	pushup(u);
}
long long query(long long u,long long l,long long r){
	if(l<=tr[u].l&&tr[u].r<=r){
		return tr[u].sum;
	}
	pushdown(u);
	long long mid=(tr[u].r+tr[u].l)/2;
	long long ans=0;  
	if(l<=mid) ans=query(u*2,l,r);
	if(mid<r) ans+=query(u*2+1,l,r);
	return ans;
}
int main(){ 
	cin>>n>>m;
	for(long long i=1;i<=n;i++){
		scanf("%lld",&a[i]);
	}
	build(1,1,n);
	while(m--){
		long long op,x,y,k;
		scanf("%lld",&op);
		if(op==1){
			scanf("%lld%lld%lld",&x,&y,&k);
			mofity(1,x,y,k);
		}
		else{
			scanf("%lld%lld",&x,&y);
			long long ans;
			ans=query(1,x,y);
			printf("%lld\n",ans);
		}
	}
	return 0;
}
2025/1/18 20:03
加载中...