codevs 1503 愚蠢的宠物

时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
题目描述 Description

大家都知道,sheep有两只可爱的宠物(一只叫神牛,一只叫神菜)。有一天,sheep带着两只宠物到狗狗家时,这两只可爱的宠物竟然迷路了……

狗狗的家因为常常遭到猫猫的攻击,所以不得不把家里前院的路修得非常复杂。狗狗家前院有N个连通的分叉结点,且只有N-1条路连接这N个节点,节点的编号是1-N(1为根节点)。sheep的宠物非常笨,他们只会向前走,不会退后(只向双亲节点走),sheep想知道他们最早什么时候会相遇(即步数最少)。

输入描述 Input Description

第1行:一个正整数N,表示节点个数。

第2~N行:两个非负整数A和B,表示A是B的双亲。(保证A,B<=n)

第N+1行:两个非负整数A和B,表示两只宠物所在节点的位置。(保证A,B<=n)

输出描述 Output Description

输出他们最早相遇的节点号。

样例输入 Sample Input

10
1 2
1 3
1 4
2 5
2 6
3 7
4 8
4 9
4 10
3 6

样例输出 Sample Output

1

数据范围及提示 Data Size & Hint

对于10%的数据,n<10^6

对于100%的数据,n<=10^6

 
并查集 || LCA 
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int p,n,a,b,flag[1000000],fa[1000000];
void shenniu(int x)
{
    if(x==0) 
    return;
    flag[x]=1;
    shenniu(fa[x]);
}
void shencai(int y)
{
    if(flag[y])
    {
      p=y;return ;
    }
    shencai(fa[y]);
}
int main()
{
    cin>>n;
    for(int i=1;i<n;++i)
    {
        cin>>a>>b;
        fa[b]=a;
    }
    cin>>a>>b;
    shenniu(a);
    shencai(b);
    cout<<p;
    return 0;
}
并查集 748ms 430B
#include <algorithm>
#include <cstdio>
#define Max 1000000
using namespace std;

struct node
{
    int next,to;
}edge[Max*2];
int dep,dfn[Max*2],head[Max*2],cnt,n,a,b;
void addedge(int u,int v)
{
    cnt++;
    edge[cnt].next=head[u];
    edge[cnt].to=v;
    head[u]=cnt;
}
void dfs(int now)
{
    dfn[now]=++dep;
    for(int i=head[now];i;i=edge[i].next)
    {
        if(!dfn[edge[i].to]) dfs(edge[i].to);
    }
}
int LCA(int a,int b)
{
    while(dfn[b]>dfn[a])
    {
        for(int i=head[b];i;i=edge[i].next)
        {
            if(dfn[edge[i].to]<dfn[b])
            b=edge[i].to;
        }
    }
    while(dfn[a]>dfn[b])
    {
        for(int i=head[a];i;i=edge[i].next)
        {
            if(dfn[edge[i].to]<dfn[a])
            a=edge[i].to;
        }
    }
    return dfn[a]<dfn[b]?a:b;
}
int main()
{
    scanf("%d",&n);n-=1;
    for(int x,y;n--;)
    {
        scanf("%d%d",&x,&y);
        addedge(x,y);
        addedge(y,x);
    }
    dfs(1);
    scanf("%d%d",&a,&b);
    if(dfn[a]>dfn[b]) swap(a,b);
    printf("%d",LCA(a,b));
    return 0;
}
LCA 236ms 948B
我们都在命运之湖上荡舟划桨,波浪起伏着而我们无法逃脱孤航。但是假使我们迷失了方向,波浪将指引我们穿越另一天的曙光。
原文地址:https://www.cnblogs.com/ruojisun/p/6570874.html