洛谷P3379最近公共祖先(LCA)

给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<math.h>
#include<set>
using namespace std;
inline int read()//快读
{
	char c = getchar(); int x = 0, f = 1;
	while (c<'0' || c>'9') { if (c == '-')f = -1; c = getchar(); }
	while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
	return x * f;
}
int n, tot = 0;
struct z {
	int t, nex;
}e[1000010];
int dep[500001];
int f[500001][22];
int lg[500001];
int head[500010];
void add(int x, int y) {
	e[++tot].t = y;
	e[tot].nex = head[x];
	head[x] = tot;
}
void dfs(int x, int fat)
{
	dep[x] = dep[fat] + 1;
	f[x][0] = fat;
	for (int i = 1; (1 << i) <= dep[x]; i++)
	{
		f[x][i] = f[f[x][i - 1]][i - 1];//2^i=2^(i-1)+2^(i-1)
	}
	for (int i = head[x]; i; i = e[i].nex)
		if (e[i].t != fat) dfs(e[i].t, x);
}
int lca(int x, int y)
{
	if (dep[x] < dep[y])
	{
		swap(x, y);
	}
	while (dep[x] != dep[y])
	{
		x = f[x][lg[dep[x] - dep[y]] - 1];
	}
	if (x == y)
	{
		return x;
	}
	for (int i = lg[dep[x]]; i >= 0; i--)
	{
		if (f[x][i] != f[y][i])
		{
			x = f[x][i];
			y = f[y][i];
		}
	}
	return f[x][0];
}
int main()
{
	int m, s, a, b, x, y;
	n = read(), m = read(), s = read();
	for (int i = 1; i < n; i++)
	{
		a = read(), b = read();
		add(a, b);
		add(b, a);
	}
	for (int i = 1; i <= n; i++)
	{
		lg[i] = lg[i - 1];
		if (i == (1 << lg[i - 1])) lg[i]++;//lg为log(i)+1
	}
	dfs(s, 0);
	for (int i = 1; i <= m; i++) {
		x = read(), y = read();
		printf("%d\n", lca(x, y));
	}
	return 0;
}

样例输入
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
样例输出
4 4 1 4 4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值