pat(甲)-1021(图的连通性的判断(dfs),连通分量的个数,根节点的判断)

1021 Deepest Root(25 分)

A graph which is connected and acyclic can be considered a tree. The hight 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

 

题意:输入一个正整数n,再输入n-1行x和y,表示x和y之间连通。如果1到n之间的点构成一个树,输出根节点最深的节点;否则输出连通分量的个数(按照格式输出)。

 

思路:一开始我想先判断是否连通,如果不连通,用并查集找有几部分。如果连通,从小到大输出读数是1的点。后来有两个点一直过不去。后来参考了网上的做法,是先用dfs判断图是否连通,如果不连通,找出连通分量的个数;如果连通,以1为根节点(因为只有1已知)找到深度最大的节点,按顺序输出。

细节部分见代码注释。

#include<iostream>
#include<vector>
#include<set>
#include<cstring>
#include<algorithm>
using namespace std;
vector <vector <int> > vc;
vector <int> tmp;
set <int> st;
int mxh;
int vis[10010];
void dfs(int node,int height)
{
	if(height>mxh) //大于平均的最大高度就存入tmp 
	{
		mxh=height;
		tmp.clear();
		tmp.push_back(node);
	}
	else if(height==mxh)
	{
		tmp.push_back(node);
	}
	vis[node]=1;
	for(int i=0;i<vc[node].size();i++)
	if(vis[vc[node][i]]==0) 
	dfs(vc[node][i],height+1);
}

int main(void)
{
	int n,k,x,y,i;
	scanf("%d",&n);
	mxh=0;
	vc.resize(n+1);  //设置大小 
	for(i=0;i<n-1;i++)
	{
		scanf("%d %d",&x,&y);
		vc[x].push_back(y);
		vc[y].push_back(x);
	}
	memset(vis,0,sizeof(vis));
	int cnt=0,s1;
	for(i=1;i<=n;i++)
	{
		if(vis[i]==0)
		{
			dfs(i,1);
			if(i==1) //以1为根节点,与2或3位根节点遍历后得到的最深的子节点相同。 
			{
				if(tmp.size()!=0) s1=tmp[0];
				for(int j=0;j<tmp.size();j++)
				st.insert(tmp[j]);
			}
			cnt++;
		}
	}
	if(cnt>=2) printf("Error: %d components\n",cnt);
	else
	{
		tmp.clear(); //先清空,再以s1为结点遍历树 
		memset(vis,0,sizeof(vis)); //注意一定要全部变成0,最大高度也要变为0
		mxh=0; 
		dfs(s1,1);
		for(i=0;i<tmp.size();i++)
		st.insert(tmp[i]); 
		for(set <int>::iterator it=st.begin();it!=st.end();it++)
		printf("%d\n",*it);
	}
	
	return 0;
}

参考文章:https://www.liuchuo.net/archives/2348

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值