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 (<=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
考查:并查集、树的深度。
#include<stdio.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v[10002];
queue<int> que;
int Tree[10002];
int ans[10002];
bool mark[10002];
int tail, n;
int find_root(int x)
{
if(Tree[x] == -1)
return x;
else
{
int tmp = find_root(Tree[x]);
Tree[x] = tmp;
return tmp;
}
}
int find_height(int x)
{
mark[x] = true;
int height_tmp = 0;
que.push(x);
que.push(-1);
while(!que.empty())
{
if(que.front() == -1)
{
height_tmp ++;
que.pop();
if(que.empty())
break;
else
que.push(-1);
}
int front = que.front();
tail = front;
for(int i = 0; i < v[front].size(); i ++)
{
if(!mark[v[front][i]])
que.push(v[front][i]);
mark[v[front][i]] = true;
}
que.pop();
}
for(int i = 1; i <= n; i ++)
mark[i] = false;
return height_tmp;
}
int main()
{
freopen("F://Temp/input.txt", "r", stdin);
scanf("%d", &n);
for(int i = 1; i <= n; i ++)
{
Tree[i] = -1;
ans[i] = 0;
mark[i] = false;
}
if(!que.empty())
que.pop();
int a, b;
for(int i = 0; i < n-1; i ++)
{
scanf("%d%d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
a = find_root(a);
b = find_root(b);
if(a != b)
Tree[a] = b;
}
int count = 0;
for(int i = 1; i <= n; i ++)
if(Tree[i] == -1)
count ++;
if(count > 1)
{
printf("Error: %d components\n", count);
return 0;
}
else
{
int height_max, head;
for(int i = 1; i <= n; i ++)
{
if(v[i].size() == 1)
{
head = i;
break;
}
}
height_max = find_height(head);
while(height_max != find_height(tail))
{
head = tail;
height_max = find_height(head);
}
int j = 0;
for(int i = 1; i <= n; i ++)
if(find_height(i) == height_max)
ans[j ++] = i;
// printf("height_max = %d\n", height_max);
// printf("j = %d\n", j);
sort(ans, ans + j);
for(int i = 0; i < j; i ++)
printf("%d\n", ans[i]);
}
return 0;
}