1021 Deepest Root (25分)

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 (≤ 1 0 4 10^4 104​​) 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
题意:

给定一个无环的无向图,这种图也可以看作一棵树,把某个顶点作为树根进行遍历,可以得到该树的最大高度,选图中不同的顶点作为树根遍历可以得到不同的树高,要求找出使树的高度为最大的图中的顶点并输出顶点序号,如果该顶点不唯一则从小到大输出序号;如果图不连通则输出 Error: 连通分量个数;

分析:

首先用深度优先搜索求出该图的连通分量个数,如果连通分量个数大于2则直接输出 Error: 连通分量个数;否则逐个对该图中的顶点作为起始点进行深度优先遍历并求出对应最大深度保存在对应顶点的深度数组中,最后找出最大值并输出其下标;

题解:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v[10001];
int visited[10001]{ 0 };
int dp[10001]{ 0 };
int max_depth = -1;
void dfs(int j, int depth) {
	visited[j] = 1; 
	max_depth = depth > max_depth ? depth : max_depth;
	for (int i = 0; i < v[j].size(); i++) {
		if (!visited[v[j][i]])
			dfs(v[j][i], depth + 1);
	}
}
int main() {
	int n,c1,c2,depth=0,k=0;
	scanf("%d", &n);
	for (int i = 0; i < n - 1; i++) {
		scanf("%d%d", &c1, &c2);
		v[c1].push_back(c2);
		v[c2].push_back(c1);
	}
	for (int i = 1; i <= n; i++) {
		if (!visited[i]) {
			dfs(i, depth);
			k++;
		}
	}
	if (k > 1)
		printf("Error: %d components\n",k);
	else {
		for (int i = 1; i <= n; i++) {
			max_depth = -1; depth = 0;
			fill(visited, visited + 10001, 0);
			dfs(i, depth);
			dp[i] = max_depth;
		}
		int m = *max_element(dp + 1, dp + n + 1);
		for (int i = 1; i <= n; i++)
			if (dp[i] == m)
				printf("%d\n", i);
	}
	return 0;
}
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页