PAT-甲级-1021 Deepest Root (25 分)

本文探讨了图论中一种特殊问题——寻找一棵无环连通图(树)的最深根,使得树的高度达到最大。通过深度优先搜索算法,遍历每个节点作为根的情况,最终找出所有可能的最深根节点。如果输入的图不是一棵树,将输出错误信息并指出连通组件的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1021 Deepest Root (25 分)

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 (≤10​4​​) 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
#include <iostream>
#include <vector>
#include <set>
using namespace std;
#define rep(i,j,k)    for(int i=j;i<k;i++)

vector<int> v[10010],index;
bool vis[10010];
int maxDep=-1;
set<int> st;
void dfs(int u,int dep){
    if(dep > maxDep){
        maxDep = dep;
        index.clear();
        index.push_back(u);
    }else if(dep == maxDep){
        index.push_back(u);
    }
    vis[u] = true;
    rep(i,0,v[u].size()){
        if(vis[v[u][i]] == false)
            dfs(v[u][i],dep+1);
    }
}
int main(){
    int n,a,b,cnt=0,s1=0;
    cin>>n;
    rep(i,0,n-1){
        cin>>a>>b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    rep(i,1,n+1){
        if(vis[i]==false){
            dfs(i,1);
            if(i == 1){
                if(index.size() != 0){
                    s1 = index[0];
                    rep(j,0,index.size())
                    st.insert(index[j]);
                }
            }
            cnt++;
        }
    }
    if(cnt >= 2)
        printf("Error: %d components",cnt);
    else{
        index.clear();
        maxDep = 0;
        fill(vis,vis+10010,false);
        dfs(s1,1);
        rep(i,0,index.size())
        st.insert(index[i]);
        for(set<int>::iterator it=st.begin();it!=st.end();it++)
            printf("%d\n",*it);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值