1503 Stupid Pets
time limit: 1 sspace limit: 128000 KBtitle level: Golden Gold SolvingView Run ResultsTitle Description
Description
As we all know, sheep has two lovely pets (one called God Ox, one called divine food). One day, sheep with two pets to the dog's home, these two cute pets unexpectedly lost ...
The dog's home was often attacked by cats, so they had to make the way to the front yard very complicated. There are n connected fork nodes in the front yard of the dog, and only the N-1 route joins the N nodes, the number of the nodes is 1-n (1 is the root node). Sheep pets are very stupid, they will only walk forward, not back (only to the parents to walk), sheep want to know when they first met (that is, the minimum number of steps).
Enter a description
Input Description
Line 1th: A positive integer n that represents the number of nodes.
Line 2~n: Two non-negative integers a and B, indicating that a is a parent of B. (Guaranteed A,b<=n)
Line n+1: Two non-negative integers a and B, indicating the location of the two pet nodes. (Guaranteed A,b<=n)
Output description
Output Description
Output the node number that they first met.
Sample input
Sample Input
10
1 2
1 3
1 4
2 5
2 6
3 7
4 8
6 {
4 10
3 6
Sample output
Sample Output
1
Data range and Tips
Data Size & Hint
For 10% of data, n<10^6
For 100% of data, n<=10^6
Category labels
Tags Click here to expand
Analysis : There is no need to use and check the set, the data must be bare MST (minimum spanning tree), direct O (n) to find LCA can be AC.
Code :
#include <cstdio>#include<iostream>using namespacestd;#defineN 10010005intfa[n],n,m;BOOLCheck[n];//data must be MSTintMain () {scanf ("%d",&N); for(intI=1, x,y;i<n;i++) {cin>>x>>y; Fa[y]=x; } int from, to; CIN>> from>>to ; while( from){//O (n) go up searchcheck[ from]=true; from=fa[ from]; } while(to) {if(Check[to]) {printf ("%d\n", to); return 0; } to=Fa[to]; } return 0;}
1503 Stupid Pets