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;
}