C: 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
就是生成一棵以0为根节点的树,问你所有的叶子节点中,高度最低且数值最小的节点序号
建立邻接矩阵然后BFS搜索就好了
#include <bits/stdc++.h>
#define N 101000
#define INF 0x3f3f3f3f
#define LL long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int rak[N];
vector<int> G[N];
int main()
{
int n,cnt,a,b,ans,ak;
queue<pair<int,int> > q;
while(cin>>n){
ans=ak=INF;
cnt=0;
for(int i=0;i<=n;++i){
G[i].clear();
rak[i]=0;
}
while(!q.empty()){
q.pop();
}
for(int i=0;i<n;++i){
cin>>a>>b;
G[a].push_back(b);
}
q.push(make_pair(0,0));
while(!q.empty()){
int tempc=q.front().first,temprank=q.front().second;
q.pop();
if(rak[tempc]>ak){
break;
}
if(G[tempc].empty()){
if(tempc<ans){
ans=tempc;
ak=temprank;
}
continue;
}
for(int i=0;i<G[tempc].size();++i){
rak[G[tempc][i]]=temprank+1;
q.push(make_pair(G[tempc][i],temprank+1));
}
}
cout<<ans<<endl;
}
}
/**********************************************************************
Problem: 1010
User: CSUzick
Language: C++
Result: AC
Time:80 ms
Memory:6700 kb
**********************************************************************/