跳到正文

个人记录

P3372 【模板】线段树 1

lirunjia约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月10日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N=100010;
typedef long long LL;
struct node{
	int l,r;
	LL sum;
	LL lazy;
}; 
LL a[N],n,m;
node t[N*4];
void pushup(int p){
	t[p].sum=t[p*2].sum+t[p*2+1].sum;
}
void pushdown(int p){
	node &root=t[p],&l=t[p*2],&r=t[p*2+1];
	if(root.lazy){
		l.lazy+=root.lazy;
		r.lazy+=root.lazy;
		l.sum+=(l.r-l.l+1)*root.lazy;
		r.sum+=(r.r-r.l+1)*root.lazy;
		root.lazy=0;
	}
}

void build(int p,int l,int r){
	if(l==r) t[p]={l,l,a[l],0};
	else{
		t[p]={l,r};
		int mid=l+r >> 1;
		build(p*2,l,mid);
		build(p*2+1,mid+1,r);
		pushup(p);
	}
}

void change(int p,int l,int r,LL d){
	if(l<=t[p].l&&r>=t[p].r){
		t[p].lazy+=d;
		t[p].sum+=(t[p].r-t[p].l+1)*d;
	}
	else{
		pushdown(p);
		int mid=t[p].l+ t[p].r >> 1;
		if(l<=mid) change(p*2,l,r,d);
		if(r>mid) change(p*2+1,l,r,d);
		pushup(p);
		
	}
}

LL find(int p,int l,int r){
	if(l<=t[p].l&&r>=t[p].r) return t[p].sum;
	pushdown(p);
	int mid=t[p].l+t[p].r >> 1;
	LL res=0;
	if(l<=mid) res+=find(p*2,l,r);
	if(r>mid) res+=find(p*2+1,l,r);
	return res;
}


int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++) cin>>a[i];
	build(1,1,n);
	while(m--){
		int op,x,y,z;
		cin>>op>>x>>y;
		if(op==1){
			cin>>z;
			change(1,x,y,z);
		}
		else{
			cout<<find(1,x,y)<<endl;
		}
	}
	return 0;
}









原文