跳到正文

算法·理论

浅谈线段树

E5Ehh2866约 13 分钟
原文
文章信息与版本

文章信息

发布
2025年9月10日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 13 分钟

版本

  1. v1当前

前言

线段树我在初一的暑假最初接触,并写了一些黄绿的模板。

线段树作为一个常用的数据结构,在很多题里都有应用。

线段树博大精深,这篇文章只能介绍其冰山一角。

线段树干了什么?

线段树维护的是半群信息。在很多情况下也是交换半群信息。

半群

给定一个集合 DD 和集合 DD 上的二元运算 ×\times 满足 D×D→DD\times D\to D。

该运算满足结合律,即 a,b,c∈D,(a×b)×c=a×(b×c)a,b,c\in D,(a\times b)\times c=a\times(b\times c)。

幺半群

比起半群,它多出来的条件是:

存在幺元满足 a,ϵ∈D,a×ϵ=ϵ×a=aa,\epsilon\in D,a\times \epsilon=\epsilon\times a=a。

交换半群

比起半群,它多出来的条件是:

该运算满足交换律,即 a,b∈D,a×b=b×aa,b\in D,a\times b=b\times a。


而对于线段树,我们需要维护两种半群:

记录信息的半群 DD 和记录 tag 的半群 MM。

那么首先我们应该考虑的是,我们需要维护什么内容?

后文均以 P8868 举例。

转化为有两个序列 X,YX,Y,每次修改 XX 或者 YY 中的连续一段区间推平,求区间历史和。

既然要区间历史和,肯定需要 ∑XiYi\sum X_iY_i。每次把它以一个贡献加进历史和 ss 里去。

要维护这个的话,考虑如何应对修改操作:

假设修改了 XX 数组的一段,变成了 aa,那么这一段的 ∑XY\sum XY 变成了 a×∑Ya\times\sum Y,因此我们还需要记录 ∑X,∑Y\sum X,\sum Y。

更普遍地,如果需要维护的东西是一个多项式,可以以此为最高项,拆成若干多项式,或者分析一个操作后,为了维护某一个值,需要其他哪些辅助值。本题同时还要维护常数项 lenlen,如果 X,YX,Y 中全都被推平过了,那么答案是一个常数乘区间长度。

对于 Tag 半群的构造,首先有 X,YX,Y 的区间推平操作,需要记录 vx,vyvx,vy。

然后给一个套路做法,记录在推平操作前 ∑XY,∑X,∑Y,len\sum XY,\sum X,\sum Y,len 对 ss 的贡献系数,分别记为 cxy,cx,cy,ccxy,cx,cy,c。

为什么要推平操作前呢,原因和区间加、区间推平操作线段树先加后推平一样,加操作需要依赖修改前的值,若先推平了就不好搞了。

现在我们构造完了信息的半群和 Tag 的半群。

然后我们需要考虑三个事:

  • 将两个信息半群合并
  • 将两个 Tag 半群合并
  • 将一个 Tag 半群作用于一个信息的半群上;

第一个是容易维护的,对应项相加即可。

第二个的话,考虑本来是 Tag yy,现在加了一个 Tag xx:

我们需要维护新的 cxy,cx,cy,ccxy,cx,cy,c。

发现我们需要知道 yy 打完之后,X,YX,Y 序列是什么样的;具体我们需要枚举 yy 的 vx,vyvx,vy 有没有值。

如果都有,则对于 ∑XY\sum XY 的更新,其实就是 x.cxy×y.vx×y.vy×lenx.cxy\times y.vx\times y.vy\times len,把和 Info 相关的,这里就是 lenlen 拿出来,则将 x.cxy×y.vx×y.vyx.cxy\times y.vx\times y.vy 作为 lenlen 的系数加上。同理计算对于 ∑X,∑Y,len\sum X,\sum Y,len 的更新,将其放入对应系数中;

最后,用 x.vx,x.vyx.vx,x.vy 更新 y.vx,y.vyy.vx,y.vy。一定要放在最后更新,因为根据定义,前面那些系数是作用于未推平的区间值上的。

对于第三个,先用 Tag 中的各项系数更新 Info 的 ss,然后再用 Tag 中的 vx,vrvx,vr 更新 Info 中的其他系数。

只要这三个东西解决了,线段树就可以轻松的实现了。

比如此题,如果 Info 和 Tag 较为复杂,可以写成单独的结构体。

代码:

C++
#include <bits/stdc++.h>
#define int unsigned long long
using namespace std;
void File(string s) { freopen((s + ".in").c_str(), "r", stdin), freopen((s + ".out").c_str(), "w", stdout); }
inline void chkmax(int &a, int b) { if (a < b) a = b; }
inline void chkmin(int &a, int b) { if (a > b) a = b; }
bool b1;
const int inf = 0x3f3f3f3f3f3f3f3f;
const int N = 250005;
int n, a[N], b[N], q;
struct Info {
	int sxy, sx, sy, len, s;
	Info (int _sxy = 0, int _sx = 0, int _sy = 0, int _len = 0, int _s = 0) {
		sxy = _sxy, sx = _sx, sy = _sy, len = _len, s = _s;
	}
	friend Info operator + (Info x, Info y) {
		return Info(x.sxy + y.sxy, x.sx + y.sx, x.sy + y.sy, x.len + y.len, x.s + y.s);
	}
};
struct Tag {
	int vx, vy; // 区间覆盖
	int cxy, cx, cy, c;
	Tag (int _vx = 0, int _vy = 0, int _cxy = 0, int _cx = 0, int _cy = 0, int _c = 0) {
		vx = _vx, vy = _vy, cxy = _cxy, cx = _cx, cy = _cy, c = _c;
	}
	bool empty() { return !(vx | vy | cxy | cx | cy | c); }
	friend Info operator + (Info x, Tag y) {
		Info res = x;
		res.s += y.cxy * x.sxy + y.cx * x.sx + y.cy * x.sy + y.c * x.len;
		if (y.vx && y.vy) {
			res = Info(y.vx * y.vy * x.len, y.vx * x.len, y.vy * x.len, x.len, res.s);
		}
		else if (y.vx) {
			res = Info(y.vx * x.sy, y.vx * x.len, x.sy, x.len, res.s);
		}
		else if (y.vy) {
			res = Info(x.sx * y.vy, x.sx, x.len * y.vy, x.len, res.s);
		}
		// else res = x;
		return res;
	}
	friend Tag operator + (Tag y, Tag x) { // put x on y, x is new
		if (y.vx && y.vy) {
			y.c += x.cxy * y.vx * y.vy + x.cx * y.vx + x.cy * y.vy + x.c;
		}
		else if (y.vx) {
			y.cy += x.cxy * y.vx + x.cy;
			y.c += x.cx * y.vx + x.c;
		}
		else if (y.vy) {
			y.cx += x.cxy * y.vy + x.cx;
			y.c += x.cy * y.vy + x.c;
		}
		else {
			y.cxy += x.cxy;
			y.cx += x.cx;
			y.cy += x.cy;
			y.c += x.c;
		}
		if (x.vx) y.vx = x.vx;
		if (x.vy) y.vy = x.vy;
		return y;
	}
};
struct Segment_tree {
	Info tr[N << 2];
	Tag tg[N << 2];
	#define ls (p << 1)
	#define rs (p << 1 | 1)
	void build(int s = 1, int t = n, int p = 1) {
		if (s == t) { tr[p].len = 1; return; }
		int m = (s + t) >> 1;
		build(s, m, ls), build(m + 1, t, rs);
		tr[p] = tr[ls] + tr[rs];
	}
	void pushdown(int p) {
		if (tg[p].empty()) return ;
		tr[ls] = tr[ls] + tg[p], tg[ls] = tg[ls] + tg[p];
		tr[rs] = tr[rs] + tg[p], tg[rs] = tg[rs] + tg[p];
		tg[p] = Tag();
	}
	void modify(int l, int r, Tag v, int s = 1, int t = n, int p = 1) {
		if (l <= s && r >= t) {
			tr[p] = tr[p] + v;
			tg[p] = tg[p] + v;
			return;
		}
		int m = (s + t) >> 1;
		pushdown(p);
		if (l <= m) modify(l, r, v, s, m, ls);
		if (r > m) modify(l, r, v, m + 1, t, rs);
		tr[p] = tr[ls] + tr[rs];
	}
	int query(int l, int r, int s = 1, int t = n, int p = 1) {
		if (l <= s && r >= t) return tr[p].s;
		int m = (s + t) >> 1, res = 0; pushdown(p);
		if (l <= m) res += query(l, r, s, m, ls);
		if (r > m) res += query(l, r, m + 1, t, rs);
		return res;
	}
} seg;
int astk[N], atp, bstk[N], btp;
vector<pair<int, int> > qd[N];
int ans[N];
bool b2;
signed main() {
	// cout << (&b2 - &b1) / 1024.0 / 1024;return 0;
	// File("match");
	int TTT;
	cin >> TTT >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1; i <= n; i++) cin >> b[i];
	seg.build();
	cin >> q;
	for (int i = 1; i <= q; i++) {
		int l, r;
		cin >> l >> r;
		qd[r].push_back(make_pair(l, i));
	}
	for (int i = 1; i <= n; i++) {
		while (atp && a[astk[atp]] < a[i]) atp--;
		while (btp && b[bstk[btp]] < b[i]) btp--;
		seg.modify(astk[atp] + 1, i, Tag(a[i], 0));
		seg.modify(bstk[btp] + 1, i, Tag(0, b[i]));
		astk[++atp] = i, bstk[++btp] = i;
		seg.modify(1, i, Tag(0, 0, 1));
		for (auto [l, id] : qd[i]) {
			ans[id] = seg.query(l, i);
		}
	}
	for (int i = 1; i <= q; i++) cout << ans[i] << '\n';
	return 0;
}

最后丢一些草稿。

s←tcxyvsxy+tcxvsx+tcyvsy+tclens\gets t_{cxy}v_{sxy}+t_{cx}v_{sx}+t_{cy}v_{sy}+t_{c}len

For a tag (vx,vy,cx,cy,cxy,c)(vx, vy, cx, cy, cxy, c), we put xx on yy:

  • If yvx,yvyy_{vx},y_{vy} both have value, then all x-s here are yvxy_{vx}, all y-s are yvyy_{vy}. Then for xyxy, ss adds xcxy×ycx×ycy×lenx_{cxy}\times y_{cx}\times y_{cy}\times len; for xx, ss adds xcx×yvx×lenx_{cx}\times y_{vx}\times len, for yy, ss adds xcy×yvy×lenx_{cy}\times y_{vy}\times len; for lenlen, ss adds xc×lenx_c\times len. So we put them in ycy_c, without lenlen.
  • If yvxy_{vx} has value, then all x-s are yvxy_{vx}. Then for xyxy, ss adds xcxy×vsy×yvxx_{cxy}\times v_{sy}\times y_{vx}, put in vsyv_{sy}; for xx, ss adds xcx×yvx×lenx_{cx}\times y_{vx}\times len, put in lenlen; for yy, ss adds xcy×vsyx_{cy}\times v_{sy}, put in vsyv_{sy}; for lenlen, ss adds xc×lenx_c\times len, put in lenlen.
  • yvyy_{vy} has value, it’s similar.
  • If neither has value. Then add the corresponding value.
原文