URAL 1056 Computer Net(最短路)

Computer Net

Time limit: 2.0 second
Memory limit: 64 MB

Background

Computer
net is created by consecutive computer plug-up to one that has already
been connected to the net. Each new computer gets an ordinal number, but
the protocol contains the number of its parent computer in the net.
Thus, protocol consists of several numbers; the first of them is always
1, because the second computer can only be connected to the first one,
the second number is 1 or 2 and so forth. The total quantity of numbers
in the protocol is N − 1 (N is a total number of computers).
For instance, protocol 1, 1, 2, 2 corresponds to the following net:
1 - 2 - 5
| |
3 4
The distance between the computers is the quantity of mutual connections (between each other) in chain. Thus, in example mentioned above the distance between computers #4 and #5 is 2, and between #3 and #5 is 3.
Definition. Let the center of the net be the computer which has a minimal distance to the most remote computer. In the shown example computers #1 and #2 are the centers of the net.

Problem

Your task is to find all the centers using the set protocol.

Input

The first line of input contains an integer N, the quantity of computers (2 ≤ N ≤ 10000). Successive N − 1 lines contain protocol.

Output

Output should contain ordinal numbers of the determined net centers in ascending order.

Sample

input output
5
1
1
2
2
1 2
Problem Source: Rybinsk State Avia Academy
【分析】给你一棵树,n个节点,n-1条边,接下来n-1行,i th行表示与i相连的节点编号,要你找几个点,使得这几个点离最远的那个点的距离最小。
 做法就是最短路找这棵树的直径,记录直径的长度,然后顺着这条直径找中点。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#define inf 0x3f3f3f3f
#define met(a,b) memset(a,b,sizeof a)
typedef long long ll;
using namespace std;
const int N = ;
const int M = ;
int vis[N],dis[N],pre[N],head[N];
int n,m,tot=,son,maxn;
struct EDG{int to,next;}edg[N*N];
void add(int u,int v){
edg[tot].to=v;edg[tot].next=head[u];head[u]=tot++;
}
void bfs(int s) {
met(vis,);met(dis,inf);met(pre,);
dis[s] = ;
vis[s] = ;maxn=;
queue<int>q;q.push(s);
while(!q.empty()){
int u=q.front();q.pop();vis[u]=;
for(int i=head[u];i!=-;i=edg[i].next){
int v=edg[i].to;
if(dis[v]>dis[u]+){
dis[v]=dis[u]+;maxn=max(maxn,dis[v]);pre[v]=u;
if(!vis[v]){
q.push(v);vis[v]=;
}
}
}
son=u;
}
}
int main() {
met(head,-);
int a[N],cnt=;
scanf("%d",&n);
for(int i=;i<=n;i++){
scanf("%d",&m);add(i,m);add(m,i);
}
bfs();int s=son;
bfs(son);int t=son;//printf("!!%d %d\n",s,t);
if(maxn&){
int x=maxn/;
while(t){
if(dis[t]==x||dis[t]==x+)a[cnt++]=t;
t=pre[t];
}
}
else {
int x=maxn/;
while(t){
if(dis[t]==x)a[cnt++]=t;
t=pre[t];
}
}
sort(a,a+cnt);
for(int i=;i<cnt;i++)printf("%d ",a[i]);
printf("\n");
return ;
}
上一篇:MVC权限管理系统dwpro项目分配按钮没有显示的问题


下一篇:hdu 3537 Daizhenyang's Coin 博弈论