HDU 2586 How far away ?【LCA】

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2586
在这里插入图片描述
★就是这题让我入坑了 LCA ,目前只会 倍增法求LCA ,所以题解也是用的倍增法(不过我看其他题解没看到用倍增的


思路:

不考虑点之间的距离(设每个点的距离为1)假设要 求 点a到点b 的距离,且已知 点a和点b 的LCA是 点t
现在用dep[ i ]表示点i的深度,那么 点a到点b的距离=dep[ a ] + dep[ b ] - 2*dep[ t ] 不明白的话可以手动画图辅助理解
但是本题加了点之间的距离,其实也没变多复杂,只需要把 点i到根的距离记录下来就好了(记为dis[ i ])
故答案为 dis[a]+dis[b]-2*dis[lca(a,b)]


代码:

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<deque>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn=4e4+5;
const int sz=1<<16;
const int inf=2e9;
const int mod=1e9+7;
const double pi=acos(-1);
typedef long long LL;
int n,m,cnt;
struct node
{
    int next;
    int to;
    int v;
}edge[maxn<<1];
int head[maxn],dep[maxn],dis[maxn];
int fa[maxn][22],lg[maxn];
template<class T>
inline void read(T &x)
{
    char c;x=1;
    while((c=getchar())<'0'||c>'9') if(c=='-') x=-1;
    T res=c-'0';
    while((c=getchar())>='0'&&c<='9') res=res*10+c-'0';
    x*=res;
}
void add_edge(int a,int b,int c)
{
    edge[++cnt].to=b;
    edge[cnt].v=c;
    edge[cnt].next=head[a];
    head[a]=cnt;
}
void dfs(int p,int f,int dist)           //p为当前点 , f为其父节点 , dist为目前的距离
{
//    cout<<p<<'x'<<endl;
    dep[p]=dep[f]+1;
    dis[p]=dist;
    fa[p][0]=f;
    for(int i=1;(1<<i)<=dep[p];i++){
        fa[p][i]=fa[fa[p][i-1]][i-1];
    }
    for(int i=head[p];i;i=edge[i].next){
        if(edge[i].to!=f)
        dfs(edge[i].to,p,dist+edge[i].v);
    }
}
int lca(int a,int b)
{
    if(dep[a]<dep[b]) swap(a,b);
    while(dep[a]>dep[b]){
        a=fa[a][lg[dep[a]-dep[b]]-1];
    }
    if(a==b) return a;
    for(int i=lg[dep[a]]-1;i>=0;i--){
        if(fa[a][i]!=fa[b][i])
            a=fa[a][i],b=fa[b][i];
    }
    return fa[a][0];
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        int s,a,b,c;
        cnt=0;
        memset(head,0,sizeof head);

        scanf("%d%d",&n,&m);
        for(int i=1;i<n;i++){
            scanf("%d%d%d",&a,&b,&c);
            add_edge(a,b,c);
            add_edge(b,a,c);
        }
        dfs(1,0,0);
        for(int i=1;i<=n;i++)
            lg[i]=lg[i-1]+(1<<lg[i-1]==i);
        while(m--){
            scanf("%d%d",&a,&b);
            printf("%d\n",dis[a]+dis[b]-2*dis[lca(a,b)]);
        }
    }
    return 0;
}

发布了71 篇原创文章 · 获赞 89 · 访问量 8557

猜你喜欢

转载自blog.csdn.net/weixin_43890662/article/details/99619973