LCA(树链剖分)

题目

emmm求树上两点的lca
luogu P3379 【模板】最近公共祖先(LCA)

题解

  • 树链剖分的讲解
  • 树剖的思路:
    • 对于在同一条链上的两个点,深度小的即为lca
    • 对于不在同一条链上的两个点,可以把它们跳到同一深度,同理即可

c o d e code code

#include <map> 
#include <set> 
#include <list> 
#include <cmath> 
#include <deque> 
#include <stack> 
#include <queue> 
#include <cstdio> 
#include <cctype> 
#include <vector> 
#include <string> 
#include <cstring> 
#include <iomanip> 
#include <complex> 
#include <iostream> 
#include <algorithm> 
#include <functional> 
using namespace std; 
typedef long long LL; 
const int maxn = 500000 + 1000; 

template <class T> 
inline void read(T &s) {
	s = 0; 
	T w = 1, ch = getchar(); 
	while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
	while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	s *= w; 
}

int n, m, s, tot; 
int lin[maxn], son[maxn], dep[maxn], siz[maxn]; 
int top[maxn], fat[maxn]; 
struct node { int next, to; } edge[maxn << 1]; 

inline void add(int from, int to) {
	edge[++tot].to = to; 
	edge[tot].next = lin[from]; 
	lin[from] = tot; 
}

void dfs1(int u, int fa, int depth) {
	siz[u] = 1; 
	fat[u] = fa; 
	dep[u] = depth; 
	int maxson = -1; 
	for (int i = lin[u]; i; i = edge[i].next) {
		int v = edge[i].to; 
		if (v == fa) continue; 
		dfs1(v, u, depth + 1); 
		siz[u] += siz[v]; 
		if (siz[v] > maxson) {
			maxson = siz[v]; 
			son[u] = v; 
		}
	}
}

void dfs2(int u, int tp) {
	top[u] = tp; 
	if (!son[u]) return ; 
	dfs2(son[u], tp); 
	for (int i = lin[u]; i; i = edge[i].next) {
		int v = edge[i].to; 
		if (v == fat[u] || v == son[u]) continue; 
		dfs2(v, v); 
	}
}

int get_lca(int x, int y) {
	while (top[x] != top[y]) {
		if (dep[top[x]] < dep[top[y]]) swap(x, y); 
		x = fat[top[x]]; 
	}
	// printf("--  %d %d --\n", x, y); 
	return dep[x] > dep[y] ? y : x; 
}

int main() {
	read(n), read(m), read(s); 
	for (int i = 1; i < n; ++i) {
		int u, v; 
		read(u), read(v); 
		add(u, v); 
		add(v, u); 
	}
	dfs1(s, 0, 1); 
	dfs2(s, s); 
	while (m--) {
		int x, y; 
		read(x), read(y); 
		printf("%d\n", get_lca(x, y)); 
	}
	return 0; 
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值