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 (<=10000) 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个结点(1~n)之间的n条边,问是否能构成一棵树,如果不能构成则输出它有的连通分量个数,如果能构成一棵树,输出能构成最深的树的高度时,树的根结点。如果有多个,按照从小到大输出。
思路
进行两次深度优先搜索,第一次任取一个结点作为根结点(为了方便起见选择1号作为根结点),将这一次遍历中最深的结点(可能不止一个)加入到向量depthestNodes中,同时计算连通分量。
- 若连通分量大于1,则输出Error: x components。
- 否则执行第二次深度优先搜索,根结点为上一轮depthestNodes中的任意一个(为了方便取第一个)。
代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#define maxN 10001
using namespace std;
bool marked[maxN];
vector<int> graph[maxN];
int maxHeight = 0;
vector<int> depthestNodes;