跳到正文

个人记录

一种美观的线段树写法

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

文章信息

发布
2023年10月5日
收录
2026年5月30日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>//eg.区间修改 区间查询
#define int long long
using namespace std;
int n,m;
struct Segment_Tree{
	#define leftson(p) p<<1
	#define rightson(p) p<<1|1
	#define push_up(p) tree[p].val=tree[leftson(p)].val+tree[rightson(p)].val
	struct STREE{
		int l,r,val,tag;
	}tree[100001<<2];
	void build(int l,int r,int p){
		tree[p].l=l,tree[p].r=r;tree[p].tag=0;
		if(l==r){
			scanf("%lld",&tree[p].val);
			return;
		}
		int mid=l+r>>1;
		build(l,mid,leftson(p));
		build(mid+1,r,rightson(p));
		push_up(p);
	}
	void spread(int p){
		if(tree[p].tag){
			tree[leftson(p)].val+=tree[p].tag*(tree[leftson(p)].r-tree[leftson(p)].l+1);
			tree[rightson(p)].val+=tree[p].tag*(tree[rightson(p)].r-tree[rightson(p)].l+1);
			tree[leftson(p)].tag+=tree[p].tag;
			tree[rightson(p)].tag+=tree[p].tag;
			tree[p].tag=0;
		}
	}
	void update(int l,int r,int k,int p){
		if(tree[p].l>=l&&tree[p].r<=r){
			tree[p].val+=k*(tree[p].r-tree[p].l+1);
			tree[p].tag+=k;
			return;
		}
		spread(p);
		int mid=tree[p].l+tree[p].r>>1;
		if(l<=mid)update(l,r,k,leftson(p));
		if(r>mid)update(l,r,k,rightson(p));
		push_up(p);
	}
	int query(int l,int r,int p){
		if(tree[p].l>=l&&tree[p].r<=r)return tree[p].val;
		spread(p);
		int mid=tree[p].l+tree[p].r>>1;
		int ans=0;
		if(l<=mid)ans+=query(l,r,leftson(p));
		if(r>mid)ans+=query(l,r,rightson(p));
		return ans;
	}
}ST;
signed main(){
	scanf("%lld",&n);
	ST.build(1,n,1);
	scanf("%lld",&m);
	for(int i=1,l,r;i<=m;i++){
		string opt;
		cin>>opt;
		if(opt=="ADD"){
			int k;
			scanf("%lld%lld%lld",&l,&r,&k);
			ST.update(l,r,k,1);
		}
		else{
			scanf("%lld%lld",&l,&r);
			printf("%lld\n",ST.query(l,r,1));
		}
	}
	return 0;
}
原文