Submit Page Summary Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 555 Solved: 193 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 Hint Source 中南大学第五届大学生程序设计竞赛
题目大意: 用一个池塘,四周排了很多列队,求最短列的队尾骆驼的编号 解题思路: 就是一棵树,从根节点bfs即可
#include<iostream> #include<cstring> #include<stack> #include<vector> #include<queue> using namespace std; const int INF=1e8; const int MAXN=100010; vector<int> rt; int son[MAXN]; int step[MAXN]; int bfs() { int cnt=0; queue<int> q; while(!q.empty()) q.pop(); int sz=rt.size(); for(int i=0;i<sz;i++) { q.push(rt[i]); step[rt[i]]=1; } int Minlen=INF; int Minid=INF; while(!q.empty()) { int fst=q.front(); q.pop(); if(son[fst]) { q.push(son[fst]); step[son[fst]]=step[fst]+1; }else { if(Minlen>step[fst]) { Minlen=step[fst]; Minid=fst; }else if(Minlen==step[fst]&&Minid>fst) { Minid=fst; } } } return Minid; } int main() { ios::sync_with_stdio(false); int n; while(cin>>n) { rt.clear(); memset(son,0,sizeof(son)); memset(step,0,sizeof(step)); int u,v; for(int i=1;i<=n;i++) { cin>>u>>v; if(u==0) rt.push_back(v); else son[u]=v; } cout<<bfs()<<endl; } return 0; }