The Happy Desert is full of sands. There is only a kind of animal called camel living on the Happy Desert. ‘Cause they live here, they need water here. Fortunately, they find a pond which is full of water in the east corner of the desert. Though small, but enough. However, they still need to stand in lines to drink the water in the pond.
Now we mark the pond with number 0, and each of the camels with a specific number, starting from 1. And we use a pair of number to show the two adjacent camels, in which the former number is closer to the pond. There may be more than one lines starting from the pond and ending in a certain camel, but each line is always straight and has no forks.
There’re multiple test cases. In each case, there is a number N (1≤N≤100000) followed by N lines of number pairs presenting the proximate two camels. There are 99999 camels at most.
For each test case, output the camel’s number who is standing in the last position of its line but is closest to the pond. If there are more than one answer, output the one with the minimal number.
1 #include<stdio.h>
2 #include<string.h>
3 #define maxn 100010
4
5 int pre[maxn], dis[maxn];
6 //pre 数组代表当前骆驼的前一个骆驼, dis 数组代表当前骆驼到水井的距离
7 int main()
8 {
9 int n;
10 while(scanf("%d", &n) != EOF){
11 int x, y, i, ans, mind;
12 memset(dis, 0, sizeof(dis));
13 //父节点初始化 并查集必备
14 for(i = 0; i < n; i++)
15 pre[i] = i;
16 for(i = 0; i < n; i++){
17 scanf("%d %d", &x, &y);
18 pre[y] = x;
19 dis[x] = 1;
20 }
21 for(mind = n + 1, ans = i = 0; i <= n; i++){//注意:mind的初始值要大于n
22 //如果dis[i]为0 即该节点无子节点
23 if(!dis[i]){
24 x = i; //x 是一个临时变量
25 //如果这个节点有父节点 递归求出距离
26 while(pre[x] != x){
27 x = pre[x];
28 dis[i]++;
29 }
30 //找出最大距离所在的骆驼
31 if(!x && dis[i] < mind){
32 mind = dis[i];
33 ans = i;
34 }
35 }
36 }
37 printf("%d\n", ans);
38 }
39 return 0;
40 }