pat 甲级 A1021 Deepest Root (25分)

题目链接:

https://pintia.cn/problem-sets/994805342720868352/problems/994805482919673856

 

题目分析:

给出N个顶点,以及N-1条边,若恰好能构成一颗树,则输出使得所有树中高度最大的根节点,否则输出连通分量的数目。

不难发现若点P作为根节点,可使得树的高度达到最大,那么当该树的叶子节点作为根节点时,可得到同样高度的树。

 

参考代码:

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

using namespace std;

bool vis[10010];
int n, maxheight = 0, a, b, t = 0, cnt = 0;
vector <int> temp;
set <int> ans;
vector< vector<int> > v;

void DFS(int node, int height){
    if(height > maxheight){
        temp.clear();
        temp.push_back(node);
        maxheight = height;
    }else if(height == maxheight)
        temp.push_back(node);
    vis[node] = true;
    for(int i = 0; i < v[node].size(); i++){
        if(vis[v[node][i]] == false)
            DFS(v[node][i], height + 1);
    }
}

int main(){
    scanf("%d",&n);
    v.resize( n + 1);
    for(int i = 0; i < n - 1; i++){
        scanf("%d %d", &a, &b);
        v[a].push_back(b);
        v[b].push_back(a);
    }
    for(int i = 1; i <= n; i++){
        if(vis[i] == false){
            DFS(i, 1);
            if(i == 1){
                if(temp.size()) t = temp[0];
                for(int j = 0; j < temp.size(); j++){
                    ans.insert(temp[j]);
                }
            }
            cnt++;
        }
    }
    if(cnt >= 2){
        printf("Error: %d components", cnt);
    }else{
        temp.clear();
        maxheight = 0;
        fill(vis, vis +10010, false);
        DFS(t, 1);
        for(int j = 0; j < temp.size(); j++){
            ans.insert(temp[j]);
        }
        for(auto it = ans.begin(); it != ans.end(); it++){
            printf("%d\n", *it);
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值