【LCA】【模板】最近公共祖先

L i n k Link Link

l u o g u   P 3379 luogu\ P3379 luogu P3379

D e s c r i p t i o n Description Description

S a m p l e Sample Sample I n p u t Input Input

5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5

S a m p l e Sample Sample O u t p u t Output Output

4
4
1	
4
4

H i n t Hint Hint

T r a i n Train Train o f of of T h o u g h t Thought Thought

倍增求LCA

C o d e Code Code

#include<iostream>
#include<cstdio>

using namespace std;

int t, m, s, n;
int h[500005], deg[500005];
int l[500005], fa[500005][21];

struct node
{
	int to, next;
}w[1000005]; 		

void add(int x, int y)
{w[++t] = (node){y, h[x]}; h[x] = t;}

void dfs(int now, int fath)
{
	fa[now][0] = fath; deg[now] = deg[fath] + 1;
	for (int i = 1; i <= l[deg[now]]; ++i)
		fa[now][i] = fa[fa[now][i - 1]][i - 1];//2^i = 2 * 2 ^ (i - 1)
	for (int i = h[now]; i; i = w[i].next)		
		if (w[i].to != fath) dfs(w[i].to, now);
}

int LCA(int x, int y)
{
	if (deg[x] < deg[y]) swap(x, y);
	while (deg[x] > deg[y])
		x = fa[x][l[deg[x] - deg[y]] - 1];//降到同一深度
	if (x == y) return x;
	for (int i = l[deg[x]] - 1; i >= 0; --i)
		if (fa[x][i] != fa[y][i]) {
			x = fa[x][i];
			y = fa[y][i];
		}
	return fa[x][0];	
}

int main()
{
	int x, y;
	scanf("%d%d%d", &n, &m, &s);
	for (int i = 1; i < n; ++i)
	{
		scanf("%d%d", &x, &y);
		add(x, y); add(y, x);
	}
	for (int i = 1; i <= n; ++i)
		l[i] = l[i - 1] + (1 << l[i - 1] == i);//求log
	dfs(s, 0);
	for (int i = 1; i <= m; ++i)
	{
		int x, y; scanf("%d%d", &x, &y);
		printf("%d\n", LCA(x, y));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值