跳到正文

算法·理论

算法总结——树链剖分

program_xwl约 18 分钟
原文
文章信息与版本

文章信息

发布
2025年5月18日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 18 分钟

版本

  1. v1当前

处理区间问题的算法和数据结构很多,但处理树上问题的却很少,树链剖分是一种将树上问题转化为区间问题的离线算法,让静态树也能拥有处理区间问题的优秀复杂度。

重链剖分

思路

每次与自己最重的儿子连链,其余开链,使树被剖分为若干个树链。可以证明从任意节点通过跳链的方式到达根的时间复杂度为 O(log⁡n)O(\log n),证明如下(其实就是启发式合并的证明):

若想构造从 sonson 节点与父亲不在一条链(也就是需要一次跳跃),说明他有一个兄弟节点的子树大小大于等于他,设他的子树大小为 xx,则其兄弟节点的子树大小 ≥x\ge x,往上跳一次,子树合并,得父节点的子树大小 >2x>2x。也就是说,每往跳链一次,他所在的节点的子树大小至少会翻一倍,设其跳了 kk 次链,那么 n>2kn>2^k 得出其复杂度为 O(log⁡n)O(\log n)。

代码

树链剖分的代码非常恶心。

树链剖分
C++
void dfs(int x,int fa)
{
	siz[x] = 1;//子树大小
	depth[x] = depth[fa]+1;//节点深度
	heavyson[x] = 0;//重儿子
	fa_t[x] = fa;//父节点
	for(auto nx:tree[x])
	{
		if(nx == fa) continue;
		dfs(nx,x);
		siz[x] += siz[nx];
		if(siz[nx] > siz[heavyson[x]]) heavyson[x] = nx;//找出重儿子
	}
	return;
}

void dfs2(int x,int fa)
{
	dfn[x] = ++tim;//标记时间戳
	id[tim] = x;//时间戳的归属标记
	if(heavyson[x] != 0)//如果有儿子,则优先进入重儿子
	{
		top[heavyson[x]] = top[x];
		dfs2(heavyson[x],x);
	}
	for(auto nx:tree[x])//处理其它儿子
	{
		if(nx == fa || nx == heavyson[x]) continue;
		top[nx] = nx;
		dfs2(nx,x);
	}
	out[x] = tim;//x子树中最大的时间戳
	return;
}
路径操作

只要是区间能解决的问题都可以多带个 log⁡\log 解决树链上问题。

C++
//对树上路径x->y做操作
while(top[x] != top[y])//两点不属于同一条链
{
	if(depth[top[x]] < depth[top[y]]) swap(x,y);//类似于LCA,左右互搏
	f(dfn[top[x]],dfn[x]);//区间操作
	x = fa_t[top[x]];//跳链
}
f(min(dfn[x],dfn[y]),max(dfn[x],dfn[y]));//两节点LCA所在链上要特别做一次
子树操作
C++
f(dfn[x],out[x]);

例题

例题1 【模板】重链剖分/树链剖分

思路

板子题

代码

C++
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5;
#define int long long
struct node {int l,r;long long sum,add;} bittree[N*4];
int n,T,root,mod,depth[N],siz[N],fa_t[N],heavyson[N],dfn[N],tim = 0,top[N],id[N],val[N],out[N];
vector<int>tree[N];

void dfs(int x,int fa)
{
	siz[x] = 1;
	depth[x] = depth[fa]+1;
	heavyson[x] = 0;
	fa_t[x] = fa;
	for(auto nx:tree[x])
	{
		if(nx == fa) continue;
		dfs(nx,x);
		siz[x] += siz[nx];
		if(siz[nx] > siz[heavyson[x]]) heavyson[x] = nx;
	}
	return;
}

void dfs2(int x,int fa)
{
	dfn[x] = ++tim;
	id[tim] = x;
	if(heavyson[x] != 0)
	{
		top[heavyson[x]] = top[x];
		dfs2(heavyson[x],x);
	}
	for(auto nx:tree[x])
	{
		if(nx == fa || nx == heavyson[x]) continue;
		top[nx] = nx;
		dfs2(nx,x);
	}
	out[x] = tim;
	return;
}

void push_down(node * tree,int x)
{
	if(tree[x].add != 0)
	{
		tree[x*2].sum = (tree[x*2].sum+tree[x].add*(tree[x*2].r-tree[x*2].l+1))%mod;
		tree[x*2+1].sum = (tree[x*2+1].sum+tree[x].add*(tree[x*2+1].r-tree[x*2+1].l+1))%mod;
		tree[x*2].add = (tree[x*2].add+tree[x].add)%mod;
		tree[x*2+1].add = (tree[x*2+1].add+tree[x].add)%mod;
		tree[x].add = 0;
	}
	return;
}

void push_up(node * tree,int x)
{
	tree[x].sum = (tree[x*2].sum+tree[x*2+1].sum)%mod;
	return;
}

void build_tree(node * tree,int pos,int l,int r)
{
	tree[pos].l = l;
	tree[pos].r = r;
	tree[pos].add = 0;
	if(l == r)
	{
		tree[pos].sum = val[id[tree[pos].l]];
		return;
	}
	int mid = (l+r)/2;
	build_tree(tree,pos*2,l,mid);
	build_tree(tree,pos*2+1,mid+1,r);
	push_up(tree,pos);
	return;
}

void change(node * tree,int pos,int l,int r,int add_val)
{
	if(l <= tree[pos].l && tree[pos].r <= r)
	{
		tree[pos].sum = (tree[pos].sum+add_val*(tree[pos].r-tree[pos].l+1))%mod;
		tree[pos].add = (tree[pos].add+add_val)%mod;
		return;
	}
	push_down(tree,pos);
	int mid = (tree[pos].l+tree[pos].r)/2;
	if(l <= mid) change(tree,pos*2,l,r,add_val);
	if(mid < r) change(tree,pos*2+1,l,r,add_val);
	push_up(tree,pos);
	return;
}

long long get_sum(node * tree,int pos,int l,int r)
{
	if(l <= tree[pos].l && tree[pos].r <= r) return tree[pos].sum;
	push_down(tree,pos);
	int mid = (tree[pos].l+tree[pos].r)/2;
	long long the_ans = 0;
	if(l <= mid) the_ans = (the_ans+get_sum(tree,pos*2,l,r))%mod;
	if(mid < r) the_ans = (the_ans+get_sum(tree,pos*2+1,l,r))%mod;
	push_up(tree,pos);
	return the_ans;
}

void add_onpath(int x,int y,int add_val)
{
	while(top[x] != top[y])
	{
		if(depth[top[x]] > depth[top[y]])
		{
			change(bittree,1,dfn[top[x]],dfn[x],add_val);
			x = fa_t[top[x]];
		}else
		{
			change(bittree,1,dfn[top[y]],dfn[y],add_val);
			y = fa_t[top[y]];
		}
	}
	change(bittree,1,min(dfn[x],dfn[y]),max(dfn[x],dfn[y]),add_val);
	return;
}

long long getsum_onpath(int x,int y)
{
	long long the_ans = 0;
	while(top[x] != top[y])
	{
		if(depth[top[x]] > depth[top[y]])
		{
			the_ans = (the_ans+get_sum(bittree,1,dfn[top[x]],dfn[x]))%mod;
			x = fa_t[top[x]];
		}else
		{
			the_ans = (the_ans+get_sum(bittree,1,dfn[top[y]],dfn[y]))%mod;
			y = fa_t[top[y]];
		}
	}
	the_ans = (the_ans+get_sum(bittree,1,min(dfn[x],dfn[y]),max(dfn[x],dfn[y])))%mod;
	return the_ans;
}

void add_tree(int x,int add_val)
{
	change(bittree,1,dfn[x],out[x],add_val);
	return;
}

long long getsum_tree(int x) {return get_sum(bittree,1,dfn[x],out[x]);}

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> T >> root >> mod;
	for(int i = 1;i <= n;i++)
	{
		cin >> val[i];
		val[i] %= mod;
	}
	for(int i = 1;i < n;i++)
	{
		int u,v;
		cin >> u >> v;
		tree[u].push_back(v);
		tree[v].push_back(u);
	}
	dfs(root,0);
	top[root] = root;
	dfs2(root,0);
	build_tree(bittree,1,1,n);
	while(T--)
	{
		int op,x,y,z;
		cin >> op;
		if(op == 1)
		{
			cin >> x >> y >> z;
			add_onpath(x,y,z%mod);
		}else if(op == 2)
		{
			cin >> x >> y;
			cout << getsum_onpath(x,y)%mod << '\n';
		}else if(op == 3)
		{
			cin >> x >> z;
			add_tree(x,z%mod);
		}else if(op == 4)
		{
			cin >> x;
			cout << getsum_tree(x)%mod << '\n';
		}
	}
	return 0;
}

例题2 [SDOI2011] 染色

思路

先把它弱化为区间问题:在线求区间颜色段数量。

区间的两端的颜色段是否会合二为一,取决于两区间接壤的部分是否相同,我们可以存储区间的左右元素,如果相同就说明重复,答案减一。区间可以合并,就可以用线段树维护了。

再套一个树链剖分使其可以求解树上问题。

代码

C++
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5;
struct node {int l,r,ans,st,lv,rv;} bittree[N*4];
int n,T,root,depth[N],siz[N],fa_t[N],heavyson[N],dfn[N],tim = 0,top[N],id[N],val[N],last_l,last_r;
vector<int>tree[N];

void dfs(int x,int fa)
{
	siz[x] = 1;
	depth[x] = depth[fa]+1;
	heavyson[x] = 0;
	fa_t[x] = fa;
	for(auto nx:tree[x])
	{
		if(nx == fa) continue;
		dfs(nx,x);
		siz[x] += siz[nx];
		if(siz[nx] > siz[heavyson[x]]) heavyson[x] = nx;
	}
	return;
}

void dfs2(int x,int fa)
{
	dfn[x] = ++tim;
	id[tim] = x;
	if(heavyson[x] != 0)
	{
		top[heavyson[x]] = top[x];
		dfs2(heavyson[x],x);
	}
	for(auto nx:tree[x])
	{
		if(nx == fa || nx == heavyson[x]) continue;
		top[nx] = nx;
		dfs2(nx,x);
	}
	return;
}

void push_down(node * tree,int x)
{
	if(tree[x].st != 0)
	{
		tree[x*2].lv = tree[x*2].rv = tree[x*2+1].lv = tree[x*2+1].rv = tree[x*2].st = tree[x*2+1].st = tree[x].st;
		tree[x*2].ans = tree[x*2+1].ans = 1;
		tree[x].st = 0;
	}
	return;
}

void push_up(node * tree,int x)
{
	tree[x].ans = tree[x*2].ans+tree[x*2+1].ans;
	if(tree[x*2].rv == tree[x*2+1].lv) tree[x].ans--;
	tree[x].lv = tree[x*2].lv;
	tree[x].rv = tree[x*2+1].rv;
	return;
}

void build_tree(node * tree,int pos,int l,int r)
{
	tree[pos].l = l;
	tree[pos].r = r;
	tree[pos].st = 0;
	if(l == r)
	{
		tree[pos].ans = 1;
		tree[pos].lv = tree[pos].rv = val[id[l]];
		return;
	}
	int mid = (l+r)/2;
	build_tree(tree,pos*2,l,mid);
	build_tree(tree,pos*2+1,mid+1,r);
	push_up(tree,pos);
	return;
}

void change(node * tree,int pos,int l,int r,int nval)
{
	if(l <= tree[pos].l && tree[pos].r <= r)
	{
		tree[pos].ans = 1;
		tree[pos].lv = tree[pos].rv = tree[pos].st = nval;
		return;
	}
	push_down(tree,pos);
	int mid = (tree[pos].l+tree[pos].r)/2;
	if(l <= mid) change(tree,pos*2,l,r,nval);
	if(mid < r) change(tree,pos*2+1,l,r,nval);
	push_up(tree,pos);
	return;
}

int get_ans(node * tree,int pos,int l,int r)
{
	if(l <= tree[pos].l && tree[pos].r <= r)
	{
		if(l == tree[pos].l) last_l = tree[pos].lv;
		if(r == tree[pos].r) last_r = tree[pos].rv;
		return tree[pos].ans;
	}
	push_down(tree,pos);
	int mid = (tree[pos].l+tree[pos].r)/2,the_ans = 0;
	if(l <= mid) the_ans = get_ans(tree,pos*2,l,r);
	if(mid < r) the_ans += get_ans(tree,pos*2+1,l,r);
	if(l <= mid && mid < r && tree[pos*2].rv == tree[pos*2+1].lv) the_ans--;
	push_up(tree,pos);
	return the_ans;
}

void set_onpath(int x,int y,int nval)
{
	while(top[x] != top[y])
	{
		if(depth[top[x]] < depth[top[y]]) swap(x,y);
		change(bittree,1,dfn[top[x]],dfn[x],nval);
		x = fa_t[top[x]];
	}
	change(bittree,1,min(dfn[x],dfn[y]),max(dfn[x],dfn[y]),nval);
	return;
}

int getans_onpath(int x,int y)
{
	int the_ans = 0,ltx = 0,lty = 0;
	while(top[x] != top[y])
	{
		if(depth[top[x]] < depth[top[y]])
		{
			swap(x,y);
			swap(ltx,lty);
		}
		the_ans += get_ans(bittree,1,dfn[top[x]],dfn[x]);
		if(ltx == last_r) the_ans--;
		ltx = last_l;
		x = fa_t[top[x]];
	}
	if(depth[x] < depth[y])
	{
		swap(x,y);
		swap(ltx,lty);
	}
	the_ans += get_ans(bittree,1,dfn[y],dfn[x]);
	if(last_r == ltx) the_ans--;
	if(last_l == lty) the_ans--;
	return the_ans;
}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> T;
	for(int i = 1;i <= n;i++) cin >> val[i];
	for(int i = 1;i < n;i++)
	{
		int u,v;
		cin >> u >> v;
		tree[u].push_back(v);
		tree[v].push_back(u); 
	}
	dfs(1,0);
	top[1] = 1;
	dfs2(1,0);
	build_tree(bittree,1,1,n);
	while(T--)
	{
		char op;
		int a,b,c;
		cin >> op >> a >> b;
		if(op == 'C')
		{
			cin >> c;
			set_onpath(a,b,c);
		}else if(op == 'Q') cout << getans_onpath(a,b) << '\n';
	}
	return 0;
}
原文