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

Solution: 

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <cstdio>
using namespace std;

vector<vector<int> > Adj;
set<int> ans, temp;
int n;

bool *vis;
int *father;


int maxHeight = -1;

void dfs(int s, int height) {
    vis[s] = true;

    if (height > maxHeight) {
        maxHeight = height;
        temp.clear();
        temp.insert(s);
    } else if (height == maxHeight) {
        temp.insert(s);
    }

    for (int i = 0; i < Adj[s].size(); i++) {
        int v = Adj[s][i];
        if (!vis[v]) {
            dfs(v, height+1);
        }
    }
}

void init() {
    for (int i = 1; i <= n; i++) {
        father[i] = i;
    }
}

int FIND(int x) {
    int a = x;
    while (x != father[x]) {
        x = father[x];
    }
    while (a != father[a]) {
        int z = a;
        a = father[z];
        father[z] = x;
    }
    return x;
}

void UNION(int a, int b) {
    int Fa = FIND(a);
    int Fb = FIND(b);
    if (Fa != Fb) {
        father[Fa] = Fb;
    }
}



int main() {
    scanf("%d", &n);
    Adj.resize(n+1);
    vis = new bool[n+1];
    father = new int[n+1];
    init();
    for (int i = 0; i < n-1; i++) {
        int u, v;
        scanf("%d%d", &u, &v);
        Adj[u].push_back(v);
        Adj[v].push_back(u);
        UNION(u, v);
    }
    fill(vis, vis+n+1, false);
    int cnt = 0;
    for (int i = 1; i <= n; i++) {
        int f = FIND(i);
        if (!vis[f]) {
            cnt++;
            vis[f] = true;
        }
    }

    if (cnt > 1) {
        printf("Error: %d components\n", cnt);
        return 0;
    }
    fill(vis, vis+n+1, false);
    dfs(1, 0);
    ans = temp;
    fill(vis, vis+n+1, false);
    dfs(*ans.begin(), 0);
    for (auto it = temp.begin(); it != temp.end(); it++) {
        ans.insert(*it);
    }
    for (auto it = ans.begin(); it != ans.end(); it++) {
        printf("%d\n", *it);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章