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 (≤104) 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
#include <bits/stdc++.h>
using namespace std;
vector <int> v[10005];
int pre[10005];
int vi[10005];
int deep=0;
int cnt;
int n;
set <int> s;
int Find(int x)
{
return x==pre[x]?x:pre[x] = Find(pre[x]);
}
void Union(int x,int y)
{
int a=Find(x);
int b=Find(y);
if(a!=b)
pre[b]=a;
}
void bfs(vector <int> V)
{
vector <int> v1;
cnt++;
for(int i=0;i<V.size();i++)
{
vi[V[i]]=1;
for(int j=0;j<v[V[i]].size();j++)
{
if(vi[v[V[i]][j]]==0)
{
vi[v[V[i]][j]]=1;
v1.push_back(v[V[i]][j]);
}
}
}
if(v1.size()==0)
{
if(cnt>=deep)
{
if(cnt>deep)
{
s.clear();
deep=cnt;
}
for(int k=0;k<V.size();k++)
{
s.insert(V[k]);
}
}
}
else
bfs(v1);
}
int main()
{
set <int>::iterator it;
cin>>n;
if(n==1)
{
cout<<1<<endl;
return 0;
}
for(int i=1;i<=n;i++)
{
pre[i]=i;
}
for(int i=1;i<n;i++)
{
int a,b;
cin>>a>>b;
Union(a,b);
v[a].push_back(b);
v[b].push_back(a);
}
vector <int> v1;
for(int i=1;i<=n;i++)
{
s.insert(Find(i));
if(v[i].size()>1)
v1.push_back(i);
}
if(s.size()>1)
cout<<"Error: "<<s.size()<<" components"<<endl;
else
{
if(v1.size()==0)
{
for(int i=1;i<=n;i++)
cout<<i<<endl;
return 0;
}
else
{
for(int i=0;i<v1.size();i++)
{
memset(vi,0,sizeof(vi));
cnt=0;
vi[v1[i]]=1;
bfs(v[v1[i]]);
}
for(it=s.begin();it!=s.end();it++)
cout<<*it<<endl;
}
}
return 0;
}
本文探讨了如何在给定的图中找到能够生成最高树的根节点,即所谓的“最深根”。通过输入节点数量及边的信息,使用广度优先搜索算法,分析连通性和树的结构,最终输出所有符合条件的最深根,或在图非树的情况下返回错误信息。
919

被折叠的 条评论
为什么被折叠?



