跳到正文

个人记录

非递归线段树

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

文章信息

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

版本

  1. v2当前
  2. v1
C++
#include <bits/stdc++.h>
#define il inline
using namespace std;
using ll = long long;
constexpr int N = 1e5 + 10;

#define lc(p) p<<1
#define rc(p) p<<1|1
int n,m,lg[N],sz[N<<1];
ll w[N<<1],tag[N<<1];
il void pushup(int p){
	w[p]=w[lc(p)]+w[rc(p)];
}
il void push(int p,ll v){
	w[p]+=sz[p]*v,tag[p]+=v;
}
il void pushdown(int p){
	if (tag[p]){
		ll &v=tag[p];
		push(lc(p),v),push(rc(p),v),v=0;
	}
}
il void pushdown(int l,int r){
	for (int i=lg[n]+1;i>=1;i--) pushdown(l>>i),pushdown(r>>i);
}
void build(){
	for (int i=1;i<=n;i++) cin >> w[i+n],sz[i+n]=1;
	lg[0]=-1;
	for (int i=1;i<=n;i++) lg[i]=lg[i>>1]+1;
	for (int i=n-1;i>=1;i--) w[i]=w[lc(i)]+w[rc(i)],sz[i]=sz[lc(i)]+sz[rc(i)];
}
ll query(int l,int r){
	l+=n,r+=n+1,pushdown(l,r);
	ll res=0;
	for (;l<r;l>>=1,r>>=1){
		if (l&1) res+=w[l++];
		if (r&1) res+=w[--r];
	} return res;
}
il void update(int l,int r,ll w){
	l+=n,r+=n+1,pushdown(l,r);
	for (int u=0,v=0;l<r;l>>=1,r>>=1){
		if (l&1) u=l,push(l++,w);
		if (r&1) v=r,push(--r,w);
		do pushup(u>>=1); while (l==r && u);
		do pushup(v>>=1); while (l==r && v);
	}
}
int main(){
	cin.tie(nullptr)->sync_with_stdio(false);
	cin >> n >> m;
	build();
	ll op,l,r,k;
	while (m--){
		cin >> op >> l >> r;
		if (op==1) cin >> k,update(l,r,k);
		else cout << query(l,r) << endl;
	}
}
原文