PAT A1021 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 (≤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
题意
给出n个结点(1~n)之间的n条边,问是否能构成⼀一棵树,如果不不能构成则输出它有的连
通分量量个数,如果能构成⼀一棵树,输出能构成最深的树的⾼高度时,树的根结点。如果有多个,按照从
⼩小到⼤大输出。
思路1
- 以无向图的邻接表的方式存储图
- 使用并查集判断是否在一个集合中,每次添加一条边的时候双向添加,修改并查集。
- 若只有一个连通分量,依次计算出所有点为根结点的最大深度,将最大的点记录下来
易错:并查集初始化,头结点初始化,边集需要开点数量的两倍 N * 2
遍历邻接表中的所有点 int i = h[u]; i != -1; i = ne[i]
代码1
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int N = 10010;
int h[N], e[N * 2], ne[N * 2], idx;
int p[N];
int findfather(int x)
{
if(x != p[x]) p[x] = findfather(p[x]);
return p[x];
}
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int dfs(int u, int father)
{
int depth = 0;
for(int i = h[u]; i != -1; i = ne[i])
{
int t = e[i];
if(father == t) continue;
depth = max(depth, dfs(t, u) + 1);
}
return depth;
}
int main()
{
int n, x, y;
scanf("%d", &n);
memset(h, -1, sizeof h);
for(int i = 1; i <= n; i++)
p[i] = i;
int k = n;
for(int i = 0; i < n - 1; i++)
{
scanf("%d%d", &x, &y);
if(findfather(x) != findfather(y))
{
k--;
p[findfather(x)] = findfather(y);
}
add(x, y), add(y, x);
}
if(k > 1)
printf("Error: %d components", k);
else
{
vector<int> ans;
int max_depth = -1;
for(int i = 1; i <= n; i++)
{
int depth = dfs(i, -1);
if(depth > max_depth)
{
max_depth = depth;
ans.clear();
ans.push_back(i);
}
else if(depth == max_depth)
ans.push_back(i);
}
for(const auto &item : ans)
printf("%d\n", item);
}
return 0;
}