URAL - 1056(DFS)

问题描述:

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.

5

1

1

2

2

1  2

题目题意:题目给我们n个点,和他们的连接方式,问那些顶点到图的最远顶点的距离是最短的。

题目分析:图比较大,用vector或者邻接表存储,枚举每个顶点去DFS找到最远距离,保存最小值的顶点

代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;

const int maxn=1e4+100;
bool vis[maxn];
int deep[maxn];
vector<int> vec[maxn],ans;

int dfs(int root)
{
    int ans=0;
    if (vec[root].size()==0) return ans;
    for (int i=0;i<vec[root].size();i++) {
        if (vis[vec[root][i]]) continue;
        vis[vec[root][i]]=true;
        ans=max(ans,dfs(vec[root][i])+1);
    }
    return ans;
}
int main()
{
    int n;
    while (scanf("%d",&n)!=EOF) {
        for (int i=2;i<=n;i++) {
            int fa;
            scanf("%d",&fa);
            vec[fa].push_back(i);
            vec[i].push_back(fa);
        }
        int Min=0x3f3f3f3f;
        for (int i=1;i<=n;i++) {
            memset (vis,false,sizeof (vis));
            vis[i]=true;
            deep[i]=dfs(i);
            Min=min(Min,deep[i]);
        }
        for (int i=1;i<=n;i++) {
            if (deep[i]==Min)
                ans.push_back(i);
        }
        for (int i=0;i<ans.size();i++) {
            if (i==ans.size()-1) printf("%d\n",ans[i]);
            else printf("%d ",ans[i]);
        }
    }
    return 0;
}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值