1552 点的距离

这是一篇关于利用最近公共祖先(LCA)计算图中两点之间距离的博客。作者通过介绍1552点的距离问题,强调了这是一个常见的模板题,解题关键在于维护节点深度和LCA。题目中,两点间的距离等于它们各自到LCA节点的深度差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1552 点的距离

我是来练习LCA的小菜鸡…
每次询问x和y之间的距离,问的这么直接,估计是个模板题
其实这个题非常的模板题,两个点的距离为两个点与LCA节点的深度之差
所以我们需要维护节点深度和最近公共祖先
然后套用公式就好了

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
const int SIZE=1e5+5;
int n,q;
int u,v;
int tot;
int depth[SIZE];
int f[SIZE];
int head[SIZE];
int st[SIZE][SIZE];//从j跳2^i到达的地方 
struct node{
	int next;
	int to;
}e[SIZE];
void add(int u,int v)
{
	tot++;
	e[tot].to=v;
	e[tot].next=head[u];
	head[u]=tot;
}
int lca(int u,int v)
{
	if(depth[u]<depth[v])swap(u,v);
	for(int i=20;i>=0;i--)
	{
		if(depth[st[i][u]]>=depth[v])
			u=st[i][u];
	}
	if(u==v) return u;//找到了
	for(int i=20;i>=0;i--)
		if(st[i][u]!=st[i][v])
            u=st[i][u],v=st[i][v];
}
void dfs(int x,int father)//计算每一个节点的深度 
{
	f[x]=father;
	for(int i=head[x];i;i=e[i].next)
	{
		if(e[i].to==father) continue;//非父亲
		depth[e[i].to]=depth[father]+1;
		dfs(e[i].to,x); 
	}
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>u>>v;
		add(u,v);
		add(v,u);
	}
	depth[1]=1;
	dfs(1,0);
	for(int i=1;i<=n;i++)
	{
		st[0][i]=f[i];//预处理st数组 
	}
	for(int i=1;i<=20;i++)
		for(int j=1;j<=n;j++)
			st[i][j]=st[i-1][st[i-1][j]];
	cin>>q;
	while(q--)
	{
		cin>>u>>v;
		cout<<depth[u]+depth[v]-2*depth[lca(u,v)];
	}
	return 0;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值