【PAT甲级 图的遍历/ 树】1021 Deepest Root (25 分)

#include<bits/stdc++.h>
using namespace std;

bool visit[10010] = {
    
    false};
vector<int> G[10010];
int N;
int Depths[10010] = {
    
    0};
int compomentNum = 0;

void DFS(int u, int depth) {
    
    
    visit[u] = true;
    Depths[u] = max(Depths[u], depth);

    for(int v: G[u])
        if(!visit[v])
            DFS(v, depth+1);
}

int main() {
    
    
    cin >> N;
    for(int i = 0;i < N-1;++i){
    
    
        int u, v;
        cin >> u >> v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    // 计算最深根
    for(int root = 1;root <= N;++root){
    
    
        fill(visit, end(visit), false);
        DFS(root, 0);
    }
    // 计算连通块数量
    fill(visit, end(visit), false);
    for(int u = 1;u <= N;++u){
    
    
        if(!visit[u]) {
    
    
            DFS(u, 0);
            compomentNum++;
        }
    }
    //输出
    if(compomentNum == 1) {
    
    
        int maxDepth = *max_element(Depths+1, Depths+N);
        for(int i = 1;i <= N;++i)
            if(Depths[i] == maxDepth)
                cout << i << endl;
    } else
        printf("Error: %d components", compomentNum);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/MYMarcoreus/article/details/114417968