1021 Deepest Root

本文探讨了一个无向图如何通过算法判断是否能构成一棵树的问题,并且如果可以构成树,则找出使得树高度最大的根节点。文章提供了一种解决方案,包括使用查并集确定连通分量及深度优先搜索(DFS)来遍历图,从而找到最大深度的根节点。

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤104) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N−1 lines follow, each describes an edge by given the two adjacent nodes' numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.


Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components

题目大意

给定一个无向图,判断其是否能构成一棵树。如果不能,输出其连通分量的个数;如果能,求构成最大深度树时的根节点,如果该节点不唯一,降序输出。


思路

查并集求得连通分量个数,不唯1不是树。

将所有节点间连通数量为一的节点,选入DFS暴力判断

依次求得最大深度即可

ps: 注意N=1的情况


C/C++ 

#include<bits/stdc++.h>
using namespace std;
vector<int> road[10001];
int N,a,b;
bool appear[10001];
void findUnion(int now); // 查并集
void findDeep(int now,int deep,int *maxDeep); // 寻找最大的深度
int main()
{
    cin >> N;
    for(int z=1;z<N;z++){
        cin >> a >> b;
        road[a].push_back(b);
        road[b].push_back(a);
    }
    vector<int> keys,result;
    int flag = 0;
    for(int z=1;z<=N;z++){
        if(road[z].size()==1) keys.push_back(z);
        if(appear[z]) continue;
        findUnion(z);
        flag++;
    }

    if(N==1) cout << 1 << endl;
    else if(flag>1) printf("Error: %d components\n",flag);
    else
    {
        memset(appear,0,sizeof appear);
        int deepKey=0,maxDeep;
        for(int x:keys){
            maxDeep = 0;
            findDeep(x,1,&maxDeep);
            if(maxDeep>deepKey) result.clear(),deepKey = maxDeep;
            if(maxDeep==deepKey) result.push_back(x);
        }
        for(int x:result) cout << x << endl;
    }
    return 0;
}
void findUnion(int now){
    if(appear[now]) return;
    appear[now] = true;
    for(int x:road[now]) findUnion(x);
}
void findDeep(int now,int deep,int *maxDeep){
    if(appear[now]) return;
    appear[now] = true;
    *maxDeep = max(*maxDeep,deep);
    for(int x:road[now]) findDeep(x,deep+1,maxDeep);
    appear[now] = false;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三块不一样的石头

十分满意,一分打赏~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值