洛谷 P3379 【模板】最近公共祖先(LCA) 题解

题目来源:

https://www.luogu.org/problemnew/show/P3379

题目描述:

 

题目描述

如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。

输入输出格式

输入格式:

第一行包含三个正整数N、M、S,分别表示树的结点个数、询问的个数和树根结点的序号。

接下来N-1行每行包含两个正整数x、y,表示x结点和y结点之间有一条直接连接的边(数据保证可以构成树)。

接下来M行每行包含两个正整数a、b,表示询问a结点和b结点的最近公共祖先。

输出格式:

输出包含M行,每行包含一个正整数,依次为每一个询问的结果。

输入输出样例

输入样例#1: 复制

5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5

输出样例#1: 复制

4
4
1
4
4

说明

时空限制:1000ms,128M

数据规模:

对于30%的数据:N<=10,M<=10

对于70%的数据:N<=10000,M<=10000

对于100%的数据:N<=500000,M<=500000

样例说明:

该树结构如下:

第一次询问:2、4的最近公共祖先,故为4。

第二次询问:3、2的最近公共祖先,故为4。

第三次询问:3、5的最近公共祖先,故为1。

第四次询问:1、2的最近公共祖先,故为4。

第五次询问:4、5的最近公共祖先,故为4。

故输出依次为4、4、1、4、4。

解题思路:

     就是一个离线tarjan+并查集的,模板,关键就是处理query的id。。

代码:

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <iomanip>
#define ll long long
const int maxn=500005;
using namespace std;
struct newt1
{
    int to,next;
}e[maxn*2];
struct newt2
{
    int id,to,next;
}query[2*maxn];
int father[maxn],ans[maxn],head1[maxn],head2[maxn],vis[maxn],cnt1,cnt2;
int n,m,S;
void addedge1(int u,int v)
{
    e[cnt1].to=v;
    e[cnt1].next=head1[u];
    head1[u]=cnt1++;
}
void addedge2(int u,int v,int id)
{
    query[cnt2].id=id;
    query[cnt2].to=v;
    query[cnt2].next=head2[u];
    head2[u]=cnt2++;
}
int fi(int x)
{
    if(x==father[x])return x;
    return father[x]=fi(father[x]);
}
void init()
{
    for(int i=1;i<=n;i++)father[i]=i;
    memset(head1,-1,sizeof(head1));
    memset(head2,-1,sizeof(head2));
}
void tarjan(int u)
{
    vis[u]=1;
    for(int i=head1[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        //cout<<u<<" "<<v<<endl;
        if(!vis[v])
        tarjan(v),father[v]=u;
    }
    for(int i=head2[u];i!=-1;i=query[i].next)
    {
        int v=query[i].to;
        if(vis[v]){
            int z=fi(v);
            ans[query[i].id]=z;
        }
    }
}
int main()
{

    scanf("%d%d%d",&n,&m,&S);
    init();
    for(int i=1;i<=n-1;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        addedge1(a,b);
        addedge1(b,a);
    }
    for(int i=1;i<=m;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        addedge2(a,b,i);
        addedge2(b,a,i);
    }
    tarjan(S);
    for(int i=1;i<=m;i++)
        printf("%d\n",ans[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40400202/article/details/81431862