PAT 1021 Deepest Root (25 分)

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 (≤ 1 0 4 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




解析

连通且没有环的图是可以看出树的。
现要求你找出使树的深度最大的结点。

首先:要判断图的连通性,可以使用DFS看看图的连通分量。
之后:以每个结点作为树根,使用BFS判断树的深度。
最后输出最大深度。
Code:

#include<cstdio>
#include<vector>
#include<algorithm>
#include<iterator>
#include<queue>
using namespace std;
vector<vector<int>> G;
bool visit[100010]{ false };
void DFS(int node) {
	visit[node] = true;
	for (auto x : G[node]) {
		if (visit[x] == false)
			DFS(x);
	}
}
int DFSTrave(int size) {
	fill(begin(visit), end(visit), false);
	int block = 0;
	for (int i = 1; i <= size; i++) {
		if (visit[i] == false) {
			DFS(i);
			block++;
		}
	}
	return block;
}
int BFS2(int node) {
	fill(begin(visit), end(visit), false);
	vector<int> dep(G.size(),0);
	int maxlayer = 0;
	queue<int> Q;
	Q.push(node);
	dep[node] = 1;
	while (!Q.empty()) {
		int temp = Q.front();
		Q.pop();
		visit[temp] = true;
		if (maxlayer < dep[temp])
			maxlayer = dep[temp];
		for (auto x : G[temp]) {
			if (visit[x] == false) {
				dep[x] = dep[temp] + 1;
				Q.push(x);
			}
		}
	}
	return maxlayer;
}
int main()
{
	int N;
	scanf("%d", &N);
	G.resize(N+1);
	int node1, node2;
	for (int i = 1; i < N; i++) {
		scanf("%d %d", &node1, &node2);
		G[node1].push_back(node2);
		G[node2].push_back(node1);
	}
	int block = DFSTrave(N);
	if (block != 1)
		printf("Error: %d components", block);
	else {
		vector<int> depth(N+1, 0);
		for (int i = 1; i <= N; i++) {
			depth[i] = BFS2(i);
		}
		int max = -1;
		for (int i = 1; i <= N; i++) {
			if (depth[i] > max)
				max = depth[i];
		}
		for (int i = 1; i <= N; i++)
			if (depth[i] == max)
				printf("%d\n", i);
	}
	return 0;
}

/*
5
1 2
1 3
1 4
2 5

*/

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/84780140
今日推荐