1021. Deepest Root (25)-PAT甲级真题(图的遍历,dfs,连通分量的个数)_柳婼的博客-CSDN博客
柳婼的解法在这里,两次dfs,还是挺好玩的。
我的解法比较暴力,就是先用并查集算连通分量(这个其实还是dfs来算会更方便),如果只有一个连通分量,那deepest root一定在仅有一条arc的点上(除了只有一个结点的树,可以一开始就特殊考虑),然后从这些点开始dfs,算出深度最高的那些root。
#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
const int maxN = 10001;
int N, u, v, maxx, layer, maxL;
int fa[maxN];
std::set<int> st, root;
std::vector<std::vector<int>> adj;
std::vector<bool> visited;
int findFather(int m){
int a = m;
while(fa[a] != a){
a = fa[a];
}
int t;
while(fa[m] != m){
t = fa[m];
fa[m] = a;
m = t;
}
return a;
}
void myUnion(int m, int n){
fa[findFather(m)] = findFather(n);
}
void dfs(int k){
visited[k] = true;
++layer;
if(layer > maxL){
maxL = layer;
}
for(int i = 0; i < adj[k].size(); ++i){
if(!visited[adj[k][i]]){
dfs(adj[k][i]);
}
}
--layer;
}
int main(){
scanf("%d", &N);
if(N == 1){
printf("1");
return 0;
}
adj.resize(N + 1);
visited.resize(N + 1);
for(int i = 1; i <= N; ++i){
fa[i] = i;
}
for(int i = 1; i < N; ++i){
scanf("%d %d", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
myUnion(u, v);
}
for(int i = 1; i <= N; ++i){
st.insert(findFather(i));
}
if(st.size() != 1){
printf("Error: %d components", st.size());
return 0;
}
maxx = 0;
for(int i = 1; i <= N; ++i){
if(adj[i].size() == 1){
maxL = 0;
layer = 0;
std::fill(visited.begin() + 1, visited.end(), false);
dfs(i);
if(maxL > maxx){
maxx = maxL;
root.clear();
root.insert(i);
} else if(maxL == maxx){
root.insert(i);
}
}
}
for(auto c : root){
printf("%d\n", c);
}
return 0;
}
题目如下:
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.文章来源:https://www.toymoban.com/news/detail-614186.html
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.文章来源地址https://www.toymoban.com/news/detail-614186.html
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
到了这里,关于1021 Deepest Root (PAT甲级)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!