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

解题思路:

这道题的意思是说,给你N个节点和N-1条边,问你能不能组成一棵树,如果可以的话求出所有能够使得树深度最大的根节点;如果不能,则要求计算出连通分量的数量。

我们知道,有N个结点N-1条边,如果只有一个连通分量,那么就可以构成一棵树,如果有两个或者两个以上的连通分量,则不能构成一棵树。

我们可以用并查集来判断一张图中有几个连通分量,具体的做法就是求好图的并查集后,计算根节点的数量,有几个根节点那么图就有几个连通分量。

当我们得知可以构成一棵树的时候,我们就需要使用DFS求得取得最大树高的叶子节点,并且记为集合A,之后从集合A中任取一个结点计算取得最大树高的叶子节点,记为集合B,最后集合A和集合B的并集就是题目要求的所有结点,按要求输出即可

#include 
#include 
#include 
#include 
using namespace std;

const int N = 100010;
vector G[N];		//邻接表

bool isRoot[N];		//记录每个结点是否是根节点
int father[N];		//并查集

int findFather(int x){
	int a = x;
	while(x != father[x]){
		x = father[x];
	}
	return x;
} 

void Union(int a, int b){
	int faa = findFather(a);
	int fab = findFather(b);
	if(faa != fab){
		father[faa] = fab;
	}
}

void init(int n){
	for(int i=1; i<=n; i++){
		father[i] = i;
	}
}

//计算连通块数量
int calBlock(int n){
	int block = 0;
	for(int i=1; i<=n; i++){
		isRoot[findFather(i)] = true;
	}
	for(int i=1; i<=n; i++){
		block += isRoot[i];
	}
	return block;
} 

int maxH = 0;
vector temp, Ans;

void DFS(int u, int height, int pre){
	if(height > maxH){
		temp.clear();
		temp.push_back(u);
		maxH = height;
	} else if(height == maxH){
		temp.push_back(u);
	}
	for(int i=0; i

 

你可能感兴趣的:(OJ题)