How far away ? HDU - 2586 lca求树上两点间最短距离

题目链接: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值