【rqnoj28】[Stupid]愚蠢的宠物

题目描述

背景

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

描述

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

N的范围《=1000000

输入格式

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

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

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

输出格式

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

样例输入

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

样例输出

1

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<string.h>
 5 #include<math.h>
 6 #define INF 1000000000
 7 using namespace std;
 8 int parent[1000001];
 9 int main()
10 {
11     int n;
12     int x,y;
13     scanf("%d",&n);
14     for(int i=1;i<=n;i++)
15         parent[i]=i;
16     for(int i=1;i<n;i++)
17     {
18         scanf("%d%d",&x,&y);
19         parent[y]=x;
20     }
21     scanf("%d%d",&x,&y);
22     while(1)
23     {
24         if(x==y)
25         {
26             printf("%d
",x);
27             return 0;
28         }
29         x=parent[x];
30         y=parent[y];
31     }
32     return 0;
33 }
原文地址:https://www.cnblogs.com/zxhl/p/4655639.html