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 (≤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
#include<iostream>
#include<vector>
#include<memory.h>
using namespace std;
int n;
const int maxn = 10001;
vector<int>v[maxn];
bool vist[maxn]{ false };
int max_depth = -1;//统计以任意节点作为根的最大深度,也就是该颗树的最大深度
int max_tmp = -1;//记录所有节点的最大深度,所有树中的最大深度
void dfs(int root, int depth)
{
if (max_depth < depth)//求最大深度
{
max_depth = depth;
}
vist[root] = true;
for (int i = 0; i < v[root].size(); i++)
{
if (!vist[v[root][i]])
{
dfs(v[root][i], depth + 1);
}
}
}
int main()
{
cin >> n;
vector<int>count;
for (int i = 0; i < n - 1; i++)
{
int value1, value2;
cin >> value1 >> value2;
v[value1].push_back(value2);
v[value2].push_back(value1);
}
for (int i = 1; i <= n; i++)
{
int cnt = 0;
max_depth = 0;
memset(vist, false, maxn);
if (i == 1)//先判断是否是联通的
{
for (int j = 1; j <= n; j++)
{
if (!vist[j])
{
cnt++;
dfs(j, 1);
}
}
if (cnt >= 2)
{
cout << "Error: " << cnt << " components";
return 0;
}
}
else
{
dfs(i, 1);
}
if (max_tmp < max_depth)//更新最大深度,并将根节点入vector
{
count.clear();
max_tmp = max_depth;
count.push_back(i);
}
else if (max_tmp == max_depth)//相等,根节点入vector
{
count.push_back(i);
}
}
for (int i = 0; i < count.size(); i++)
{
cout << count[i] << endl;
}
}