CU1010: Water Drinking

题目:

Description
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.

Input
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.

Output
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.

Sample Input
1
0 1
5
0 2
0 1
1 4
2 3
3 5
5
1 3
0 2
0 1
0 4
4 5
Sample Output
1
4
2
题意:

给出一棵树,找出其最小的叶子节点,如果有多个叶子节点,
输出最小的编号。
具体见注释。

#include<iostream>
#include<stdio.h>
using namespace std;
int fa[100005], deep[100005], isfa[100005];//从左至右分别是父节点,下一级节点,是否为父节点 
int getdeep(int k)//返回一支队伍的排队序列数 
{
    if(deep[k]) return deep[k];//如果此节点已在该队列中,直接返回序数 
    int d=getdeep(fa[k]);//继承父节点序数 
    deep[k]=d+1;//序数加一 
    return deep[k];
}
int main()
{
    int n,a,b;
    while(cin>>n) 
    {
    for(int i=0;i<=n;i++) isfa[i]=0;
    for(int i=0;i<n;i++)
    {
        cin>>a>>b;
        fa[b]=a,isfa[a]=1;
    }
    for(int i=0;i<=n;i++)
    {
        deep[i]=0;
    }
    deep[0]=1;//池塘队列序数为1 
    for(int i=0;i<=n;i++) getdeep(i);//有n+1个节点 
    int minn=100005;
    for(int i=1;i<=n;i++) if(isfa[i]==0 && minn>deep[i]) minn=deep[i]; 
    for(int i=1;i<=n;i++) if(isfa[i]==0 && minn==deep[i])//找出最小的队列序数 
    {
        cout<<i<<endl;
        break;//如果队列序数相同,输出最小的编号 
    }
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值