1021 Deepest Root (25 分)(树的遍历)

1021 Deepest Root (25 分)(树的遍历)

A graph which is connected and acyclic can be considered a tree. The hight 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
分析:

本题考查树的遍历,具体的做法是:在判断连通图的个数过程中,将deeproot收集到set中,然后当图只有一个连通域时,任选set中一个点作为root,一次深度优先遍历,收集deeproot,做两次dfs后合并的deeproot即为题目要求的root

注:开始的时候错误进行了1+x2次(x是第一次收集的节点数),导致测试点超时,其实只需在第一次收集的节点中任选一个节点,进行dfs即可找出所以deeproot。因为第一次收集的节点间位置是等价的。

#include <iostream> 
#include <set> 
#include <vector> 

using namespace std;
const int inf=99999;
set<int> ans,ans1,ans2;
int maxheight=-1;
int n;
vector<vector<int> > v;
vector<bool> visit;
void dfs(int u,int height){
    visit[u]=true;
    if(height>maxheight){
        ans.clear();
        ans.insert(u);
        maxheight=height;
    }else if(height==maxheight){
        ans.insert(u);
    }
    for(int i=0;i<v[u].size();i++){
        if(!visit[v[u][i]]) dfs(v[u][i],height+1);
    }
}
int main(){ 
    int cnt=0;
    scanf("%d",&n); 
    v.resize(n+1),visit.resize(n+1);
    for(int i=1;i<=n-1;i++){
        int a,b;
        scanf("%d %d",&a,&b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    for(int i=1;i<=n;i++){
        if(!visit[i]) {
            dfs(i,0);
            cnt++;
        }
    }
    if(cnt!=1){
        printf("Error: %d components",cnt);
        return 0;
    }
    ans2=ans;
    maxheight=-1;
    fill(visit.begin(),visit.end(),false);
    ans.clear();
    dfs(*(ans2.begin()),0);
    for(auto k : ans) ans2.insert(k);
    for(auto it : ans2) printf("%d\n",it);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值