题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805482919673856
题目分析:
给出N个顶点,以及N-1条边,若恰好能构成一颗树,则输出使得所有树中高度最大的根节点,否则输出连通分量的数目。
不难发现若点P作为根节点,可使得树的高度达到最大,那么当该树的叶子节点作为根节点时,可得到同样高度的树。
参考代码:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
bool vis[10010];
int n, maxheight = 0, a, b, t = 0, cnt = 0;
vector <int> temp;
set <int> ans;
vector< vector<int> > v;
void DFS(int node, int height){
if(height > maxheight){
temp.clear();
temp.push_back(node);
maxheight = height;
}else if(height == maxheight)
temp.push_back(node);
vis[node] = true;
for(int i = 0; i < v[node].size(); i++){
if(vis[v[node][i]] == false)
DFS(v[node][i], height + 1);
}
}
int main(){
scanf("%d",&n);
v.resize( n + 1);
for(int i = 0; i < n - 1; i++){
scanf("%d %d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
for(int i = 1; i <= n; i++){
if(vis[i] == false){
DFS(i, 1);
if(i == 1){
if(temp.size()) t = temp[0];
for(int j = 0; j < temp.size(); j++){
ans.insert(temp[j]);
}
}
cnt++;
}
}
if(cnt >= 2){
printf("Error: %d components", cnt);
}else{
temp.clear();
maxheight = 0;
fill(vis, vis +10010, false);
DFS(t, 1);
for(int j = 0; j < temp.size(); j++){
ans.insert(temp[j]);
}
for(auto it = ans.begin(); it != ans.end(); it++){
printf("%d\n", *it);
}
}
return 0;
}