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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
/*
* 1.首先判断图是不是树 即是否连通和图中是否有环(这里有n个节点 n-1条边 所以连通必然无环 故使用并查集判断图是否连通即可)
* 2.求以i为根 求树高最大的根i 有多个这样的i 则按顺序输出
* 用vector数组来存储图 dfs求最大高度 因为只有10000个节点 故每次dfs最多递归10000次 不会爆栈的- - 最多执行10000次dfs 每个dfs处理
时间为O(1) 故总时间复杂度为O(n^2) 不会超时- -当然我是交了之后 才来事后诸葛亮的 QvQ...
*/
#include "iostream"
#include "cstring"
#include "algorithm"
#include "vector"
#include "queue"
using namespace std;
int father[10001];
int k;
vector<int>v[10001];
void Init(int n) {
for (int i = 1; i <= n; i++) {
father[i] = -1;
}
}
int Find(int x) {
if (father[x] <= -1) {
return x;
}
else {
return father[x] = Find(father[x]);
}
}
void Union(int x, int y) {
x = Find(x);
y = Find(y);
if (father[x] < father[y]) {
father[x] += father[y];
father[y] = x;
k--;
}
else {
father[y] += father[x];
father[x] = y;
k--;
}
}
int Max = 0;
bool vis[10001] = {false};
int h[10001] = { 0 };
void dfs(int x,int height) {
if (height > Max)
Max = height;
int len = v[x].size();
for (int i = 0; i < len; i++) {
if (!vis[v[x][i]]) {
vis[v[x][i]] = 1;
dfs(v[x][i], height + 1);
}
}
}
int main() {
int n;
cin >> n;
k = n;
Init(n);
for (int i = 1; i <= n - 1; i++) {
int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
if (Find(a) != Find(b)) {
Union(a, b);
}
}
if (k != 1) { /*图不是树 输出有几个连通分量 */
cout << "Error: " << k << " components" << endl;
}
else { /* 图是树 */
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
Max = 0;
vis[i] = 1;
dfs(i, 0);
h[i] = Max;
}
int p[10001];
memcpy(p, h, sizeof(h));
sort(h+1, h + n);
bool flag = 1;
for (int i = 1; i <=n; i++) {
if (p[i] == h[n])
cout << i<<endl;
}
}
return 0;
}