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 (<=10000) 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<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 10010;

vector<int> G[maxn];
int father[maxn];
bool isRoot[maxn];

int findFather(int x){
    int a = x;
    while(x != father[x]){  //找到x的根节点 
        x = father[x];
    }
    while(a != father[a]){   //路径压缩 
        int z = a;
        a = father[a];
        father[z] = x;
    }
    return x;
}

int calBlock(int n){    //查图中几个连通 
    int block = 0;   //未初始化 
    for(int i = 1; i <= n; i++){        
        isRoot[findFather(i)] = true;        
    }
    for(int i = 1; i <= n; i++){
        block += isRoot[i];
    }
    return block;
}

void Union(int a,int b){
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB) father[faA] = faB;
}
void init(int n){
    for(int i = 1; i <= n; i++){
       father[i] = i;        
    }
}
int maxH = 0;
vector<int> temp,ans;//临时存放最长结点
void DFS(int u,int depth,int pre) {//当前访问结点,结点深度,父节点
    if(depth > maxH){
        temp.clear();
        temp.push_back(u);
        maxH = depth;
    }else if(depth == maxH){
        temp.push_back(u);
    }
    for(int i = 0; i < G[u].size(); i++){
        if(G[u][i] == pre) continue;
        DFS(G[u][i],depth+1,u);
    }
} 


int main(){
    int n,u,v;
    int i;
    scanf("%d",&n);
    init(n);
    for(i = 1; i < n; i++){   //五个顶点,四条边。 多了一个输入 
        scanf("%d%d",&u,&v);
        G[u].push_back(v);
        G[v].push_back(u);
        Union(u,v);
    }
    int block = calBlock(n);
    if(block != 1) printf("Error: %d components",block);
    else{
        DFS(1,1,-1);
        ans = temp;
        DFS(ans[0],1,-1);
        for(i = 0; i < temp.size(); i++){
            ans.push_back(temp[i]);
        }
        sort(ans.begin(),ans.end());   //默认递增
        printf("%d
",ans[0]);
        for(i = 1; i < ans.size(); i++){
            if(ans[i] != ans[i - 1]){
                printf("%d
",ans[i]);
            }
        } 
    }
   
    return 0;
} 
原文地址:https://www.cnblogs.com/wanghao-boke/p/8575876.html