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 (≤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

思路

  • 以每个未访问的结点为根结点进行 DFS,可以求出该图的连通分量,若不为 1,则表示不为树。同时,将以第一个结点作为树的根结点进行 DFS 时所得到的最高高度的相应叶子结点插入 set 集合 ans 中,此为第一个结点集合。在第一个集合中随机选取一个结点作为根结点(这里选取了 ans 集合中的第一个元素),再次进行一遍 DFS,得到第二个结点集合。这两个结点集合的并集,即为题目所求最深根结点。
#include <cstdio>
#include <set>
#include <vector>
#include <cstring>
using namespace std;

const int maxn = 10001;
vector<int> G[maxn], temp;
set<int> ans;
int n, maxLevel = 0, cnt = 0;
bool vis[maxn] = {false};

void DFS(int root, int level) {
    vis[root] = true;
    if (level > maxLevel) {
        maxLevel = level;
        temp.clear();
        temp.push_back(root);
    } else if (level == maxLevel) {
        temp.push_back(root);
    }
    for (int i = 0; i < G[root].size(); i++) {
        if (vis[G[root][i]] == false) {
            DFS(G[root][i], level + 1);
        }
    }
}

int main() {
    scanf("%d", &n);
    int v1, v2;
    for (int i = 0; i < n - 1; i++) {
        scanf("%d %d", &v1, &v2);
        G[v1].push_back(v2);
        G[v2].push_back(v1);
    }
    for (int i = 1; i <= n; i++) {
        if (vis[i] == false) {
            cnt++;
            DFS(i, 1);
            if (i == 1) {
                for (int i = 0; i < temp.size(); i++) {
                    ans.insert(temp[i]);
                }
            }
        }
    }
    if (cnt != 1) {
        printf("Error: %d components", cnt);
    } else {
        temp.clear();
        memset(vis + 1, false, n);
        DFS(*(ans.begin()), 1);
        for (int i = 0; i < temp.size(); i++) {
            ans.insert(temp[i]);
        }
        for (auto it = ans.begin(); it != ans.end(); it++) {
            printf("%d\n", *it);
        }
    }
    return 0;
}