跳到正文

个人记录

重链剖分

Kingsley_qu约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年3月17日
收录
2026年8月25日
更新
2026年11月8日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;

#define int long long
const int M = 100005;
vector <int> edge[M];
int fa[M];
int dfn[M], tot; // 遍历到点的时间 
int dep[M], top[M], son[M], sz[M]; // 深度和父亲,所在重链最小的点

void dfs1(int x, int f)
{
	dep[x] = dep[f] + 1;
	sz[x] = 1;
	fa[x] = f;
	for(int y : edge[x])
	{
		if(y == f) continue;
		dfs1(y, x);
		sz[x] += sz[y];
		if(sz[son[x]] < sz[y]) son[x] = y;
	}
} // 找重儿子

void dfs2(int x, int f, int tp)
{
	top[x] = tp; dfn[x] = ++tot;
	if(son[x]) dfs2(son[x], x, tp);
	for(int y : edge[x])
	{
		if(y == f || y == son[x]) continue;
		dfs2(y, x, y);
	}
}// 拉链,标dfn

//好处:没有四则运算,只有赋值,将近0的常数
int lca(int x, int y) // 线段树debug技巧,打印top数组
{
	while(top[x] != top[y])
	{
		if(dep[top[x]] < dep[top[y]]) x = fa[top[x]]; // top[x] --> x 的编号是连续的 [dfn[top[x]], dfn[x]]
		else y = fa[top[y]]; // tree.query(dfn[top[y]], dfn[y])
	}
	if(dep[x] > dep[y]) swap(x, y);
	// tree.query(dfn[x], dfn[y])
	return dep[x] < dep[y] ? x : y;
}

signed main()
{

    return 0;
}
原文