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
#include
#include
#include
#include
using namespace std;
vector  > vc;
vector  tmp;
set  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=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::iterator it=st.begin();it!=st.end();it++)
		printf("%d\n",*it);
	}
	
	return 0;
}

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

你可能感兴趣的:(PAT)