1021. Deepest Root (25)

来源:互联网 发布:淘宝运费险怎么退 编辑:程序博客网 时间:2024/06/10 08:00

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

//主要就是用并查集 求连通分量,,,然后如果是一个的话,就是一棵树,然后再求数上能dfs最深的结点;按 顺序输出;

#include <bits/stdc++.h>using namespace std;const int MAXN = 10000+5;int n;int f[MAXN];bool vis[MAXN];int d[MAXN];//record the deeppest of every node.vector<int> ma[MAXN];int dfs( int s ) {    int ans = 0;    if ( vis[s] ) return 0;    vis[s] = true;    int m = ma[s].size();    for ( int i = 0; i < m; i++ ) {        if ( !vis[ma[s][i]] ) {            int tmp = dfs(ma[s][i]);            ans = max(ans, tmp);        }    }    return ans+1;}void init() {    for ( int i = 0; i <= n ; i++ ) {        f[i] = i;    }}int find( int x ) {    if ( f[x] != x ) {        f[x] = find(f[x]);    }    return f[x];}void merge( int x, int y ) {    int s1 = find(x);    int s2 = find(y);    if ( s1 != s2 ) f[s2] = s1;    else return;}int main(){    scanf("%d", &n);    init();    for ( int i = 1; i < n; i++ ) {        int s, e;        scanf("%d %d", &s, &e);        merge(s, e);        ma[s].push_back(e);        ma[e].push_back(s);    }    int sum = 0;    for ( int i = 1; i <= n; i++ ) {        if ( f[i] == i ) sum++;    }    if ( sum > 1 ) {        printf("Error: %d components\n", sum);        return 0;    } else {        for ( int i = 1; i <= n; i++ ) {            memset(vis, false, sizeof(vis));            d[i] = dfs(i);        }        int maxv = -1, index = 0;        for ( int i = 1; i <= n; i++ ) if ( d[i] > maxv ) { maxv = d[i]; index = i;}        for ( int i = 1; i <= n; i++ ) {            if ( d[i] == d[index] ) {                printf("%d\n",i);            }        }    }    return 0;}
原创粉丝点击