题目链接:https://vjudge.net/problem/HDU-2586#author=zzuli_practice
题意:给一颗树,求树上两点间最短距离。
思路:dist【i】表示根到i的距离。设z为xy的lca,xy的最短距离为dist【x】+dist【y】-2*dist【z】。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct zzz
{
int t, nex,w;
} e[40010 << 1];
int head[40010], tot,dist[40005];
void add(int x, int y,int w)
{
e[++tot].t = y;
e[tot].w=w;
e[tot].nex = head[x];
head[x] = tot;
}
int depth[40010], fa[40010][22], lg[40010];
void dfs(int now, int fath)
{
fa[now][0] = fath;
depth[now] = depth[fath] + 1;
for(int i = 1; i <= lg[depth[now]]; ++i)
fa[now][i] = fa[fa[now][i-1]][i-1];
for(int i = head[now]; i; i = e[i].nex)
{
if(e[i].t != fath)
{
dist[e[i].t]=dist[now]+e[i].w;
dfs(e[i].t, now);
}
}
}
int LCA(int x, int y)
{
if(depth[x] < depth[y])
swap(x, y);
while(depth[x] > depth[y])
x = fa[x][lg[depth[x]-depth[y]] - 1];
if(x == y)
return x;
for(int k = lg[depth[x]] - 1; k >= 0; --k)
if(fa[x][k] != fa[y][k])
x = fa[x][k], y = fa[y][k];
return fa[x][0];
}
int vis[40005];
int main()
{
int T;
scanf("%d",&T);
for(int i = 1; i <= 40005; ++i)
lg[i] = lg[i-1] + (1 << lg[i-1] == i);
while(T--)
{
memset(depth,0,sizeof(depth));
memset(fa,0,sizeof(fa));
memset(e,0,sizeof(e));
memset(vis,0,sizeof(vis));
memset(head,0,sizeof(head));
memset(dist,0,sizeof(dist));
tot=0;
int n,m;
scanf("%d%d",&n,&m);
for(int i=0; i<n-1; i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
vis[y]=1;
}
int root;
for(int i=1; i<=n; i++)
{
if(!vis[i])
{
root=i;
break;
}
}
dist[root]=0;
dfs(root,0);
int x,y;
for(int i=0; i<m; i++)
{
scanf("%d%d",&x,&y);
int z=LCA(x,y);
int d=dist[x]+dist[y]-2*dist[z];
printf("%d\n",d);
}
}
return 0;
}