1021 Deepest Root 25

 

 

#include <cstdio>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 10010;
int n,maxDepth=0,vis[maxn];
vector<int> G[maxn],ans,temp;

void dfs(int idx){
    vis[idx] = 1;
    for(int i = 0; i < G[idx].size(); i++){
        if(vis[G[idx][i]] == 0){
            dfs(G[idx][i]);
        }
    }
}
void TDFS(int root, int depth, int pre){
    vis[root] = 1;
    if(depth > maxDepth){
        maxDepth = depth;
        temp.clear();
        temp.push_back(root);
    }else if(depth == maxDepth){
        temp.push_back(root);
    }
    for(int i = 0; i < G[root].size(); i++){
        if(G[root][i] != pre){
        // if(vis[G[root][i]] == 0){
            TDFS(G[root][i], depth+1, root);
        }
    }
}

int main() {
    scanf("%d", &n);
    //n=1
    if(n == 1){
        printf("%d\n", 1);
        return 0;
    }
    int from,to;
    for(int i = 0; i < n-1; i++){
        scanf("%d%d", &from, &to);
        G[from].push_back(to);
        G[to].push_back(from);
    }
    //判断是否是一个连通图
    int block = 0;
    fill(vis, vis+maxn, 0);
    for(int i = 1; i <= n; i++){
        if(vis[i] == 0){
            dfs(i);
            block++;
        }
    }
    if(block != 1){
        printf("Error: %d components\n", block);
        return 0;
    }
    TDFS(1,1,-1);
    ans = temp;
    TDFS(ans[0],1,-1);
    for(int i = 0; i < temp.size(); i++){
        ans.push_back(temp[i]);
    }
    sort(ans.begin(), ans.end());
    printf("%d\n", ans[0]);
    for(int i = 1; i < ans.size(); i++){
        if(ans[i] != ans[i-1]){
            printf("%d\n", ans[i]);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值