题目链接:https://www.luogu.org/problemnew/show/P3379

AC代码:

#include<iostream>
#include<stack>
#include<queue>
#include<map>
#include<stdio.h>
#include<cstring>
#include<string>
#include<iomanip>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
# define ll long long
const int maxn = 500000+1010;
# define inf 0x3f3f3f3f
struct node
{
    int to;
    int nex;
} edge[maxn*2];
int head[maxn*2],depth[maxn*2],father[maxn][22];
int n,m,k,num;
void addedge(int fr,int to)
{
    edge[num].to=to;
    edge[num].nex=head[fr];
    head[fr]=num++;
}
void dfs(int u,int root)
{
    depth[u]=depth[root]+1;
    father[u][0]=root;
    for(int i=1; (1<<i)<=depth[u]; i++)//能往上更新多少就更新多少
    {
        father[u][i]=father[father[u][i-1]][i-1];
    }
    for(int i=head[u]; i!=-1; i=edge[i].nex)
    {
        int v=edge[i].to;
        if(v==root)continue;
        dfs(v,u);
    }
}
int lca(int t1,int t2)
{
    if(depth[t1]>depth[t2])swap(t1,t2);
    for(int i=20; i>=0; i--)//和下面的一样,要从小的开始凑,否则到后面会凑不出来
    {
        if(depth[t1]<=depth[t2]-(1<<i))//先调整到同一个高度
        {
            t2=father[t2][i];
        }
    }
    if(t1==t2)return t1;
    for(int i=20; i>=0; i--)
    {
        if(father[t1][i]!=father[t2][i])//一起往上找
        {
            t1=father[t1][i];
            t2=father[t2][i];
        }
    }
    return father[t1][0];
}
int main()
{
    num=0;
    memset(head,-1,sizeof(head));
    int t1,t2;
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1; i<=n-1; i++)
    {
        scanf("%d%d",&t1,&t2);
        addedge(t1,t2);
        addedge(t2,t1);
    }
    dfs(k,k);
//    for(int i=1;i<=n;i++){
//    cout<<i<<" "<<depth[i]<<endl;
//    }
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d",&t1,&t2);
        printf("%d\n",lca(t1,t2));
    }
    return 0;
}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐