树链剖分—轻重链剖分(模板)+最近公共祖先

目录

树链剖分:

最近公共祖先


 

树链剖分:

用于对树的子树和路径操作

原理:将树剖成一条条不相交的从祖先到子孙的链

设size[x]表示x点的子树大小

size[x] = 1 + sum(size[y), 其中y是x的儿子。

对于每个点x, 将儿子中size最大的那个儿子作为它的重儿子,剩下的作为轻儿子

重边:连接x和x重儿子的边

轻边:连接x和x轻儿子的边

重链:重边连起来形成的链。每个点恰好属于一条重链。

预处理出d[x]表示x的深度

预处理出f[x]表示x的父亲

预处理出size[x]表示x点的子树大小

预处理出son[x]表示x的重儿子

预处理出top[x]表示x所在重链的顶端

预处理可以通过两遍DFS在O(n)时间内完成

第一遍DFS算出size[x], d[x],f[x],并找到重儿子son[x].

第二遍DFS算出top[x],x和x的重儿子的top相同

最近公共祖先

定义:有根树上x到根的距离

最近公共祖先lca:u和v的最近公共祖先lca(u,v)定义为u到v路径上深度最小的点

任何一条路径都能表示成lca(u, v)以及v到lca(u, v)这两段深度严格递减的链。

#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
#define N 500005
struct node{
	int to;
	int nex;
}e[N<<1];
int head[N], tot = 1;
int size[N], d[N], f[N], son[N], top[N];
void init(){
	tot = 1;
	memset(size, 0, sizeof(size));
	memset(d, 0, sizeof(d));
	memset(f, 0, sizeof(f));
	memset(son, 0, sizeof(son));
	memset(top, 0, sizeof(top));
	memset(head, 0, sizeof(head));
}
void add(int x, int y){
	e[tot].to = y;
	e[tot].nex = head[x];
	head[x] = tot++;
}
void dfs1(int x, int fath){
	d[x] = d[fath] + 1;
	size[x] = 1;
	f[x] = fath;
	son[x] = 0;
	for(int i = head[x]; i; i = e[i].nex){
		int to = e[i].to;
		if(to == fath){
			continue;
		}
		dfs1(to, x);
		size[x] += size[to];
		if(size[son[x]] < size[to]){
			son[x] = to;
		}
	}
}
void dfs2(int x, int topx){
	top[x] = topx;
	if(son[x] != 0){
		dfs2(son[x], topx);
	}
	for(int i = head[x]; i; i = e[i].nex){
		if(e[i].to != f[x] && e[i].to != son[x]){
			dfs2(e[i].to, e[i].to);
		}
	}
}
int solve(int x, int y){
	while(top[x] != top[y]){
		if(d[top[x]] < d[top[y]]){
			swap(x, y);
		}
		x = f[top[x]];
	}
	return d[x] < d[y] ? x : y;
}
int main(){
	ios::sync_with_stdio(false);
	int n, m, s;
	while(cin >> n >> m >> s){
		init();
		int x, y;
		for(int i = 0; i < n - 1; i++){
			cin >> x >> y;
			add(x, y);
			add(y, x);
		}
		dfs1(s, 0);
		dfs2(s, s);
		for(int i = 0; i < m; i++){
			cin >> x >> y;
			cout << solve(x, y) << endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值