1021 Deepest Root

本文探讨了如何在给定的图中找到能够生成最高树的根节点,即所谓的“最深根”。通过输入节点数量及边的信息,使用广度优先搜索算法,分析连通性和树的结构,最终输出所有符合条件的最深根,或在图非树的情况下返回错误信息。

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

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值