LCA板子

最近公共祖先

仅仅记录板子

#include<bits/stdc++.h>
#define ios ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long 
#define pii pair<int,int>

using namespace std;

const int N = 5e5+10, M = 2*N;
int n, m, s;
int e[M], nex[M], h[N], idx;
int depth[N], fa[N][30];
void add(int a, int b){
	e[++idx] = b;
	nex[idx] = h[a];
	h[a] = idx;
}
void dfs(int x, int f){
	depth[x] = depth[f] + 1;
	fa[x][0] = f;
	for(int i = 1;i <= 20;i++){
		fa[x][i] = fa[fa[x][i-1]][i-1];
	}
	for(int i = h[x]; ~i; i = nex[i]){
		if(e[i] != f){
			dfs(e[i], x);
		}
	}
}
int getRes(int x, int y){
	for(int i = 20;i >= 0;i--){
		if(depth[fa[x][i]] >= depth[y]){
			x = fa[x][i];
		}
		
	}
	return x;
}
int LCA(int x, int y){
	if(depth[x] < depth[y])swap(x, y);
	x = getRes(x, y);
	if(x == y)return y;
	for(int i = 20;i >= 0;i--){
		if(fa[x][i] != fa[y][i]){
			x = fa[x][i];
			y = fa[y][i];
		}
	}
	return fa[x][0];
}
int main(){
	ios;
	string c = "P3379_1.in";
	// freopen(c.c_str(),"r",stdin);
	memset(h, -1, sizeof h);
	cin >> n >> m >> s;
	for(int i = 0;i < n-1;i++){
		int x, y;
		cin >> x >> y;
		add(x, y);
		add(y, x);
	}
	dfs(s, 0);
	for(int i = 0;i < m;i++){
		int x, y;
		cin >> x >> y;
		cout << LCA(x, y) << "\n";
	}
	// fclose(stdin);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值