题目地址

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 (≤10
​4
​​ ) 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

作者: CHEN, Yue
单位: 浙江大学
时间限制: 2000 ms
内存限制: 64 MB

#include <iostream>
#include <vector>
#include<algorithm>
#include <cmath>
#include<map>           //要改unordered;
#include<string>
#include<set>
#include<cstring>
using namespace std;
const int maxn=10010;
vector<int>v[maxn];int vis[maxn]={0};set<int>ans[maxn];
int n,max_dep=-1;
void dfs(int idx,int dep,int r_i){          //dfs带着pre优化,只要让他不走回头路就可以了;递归函数pre为当前idx;这样就不用循环访问dfs了;
    if(vis[idx]) return;
    ans[dep].insert(r_i);
    if(dep>max_dep){
          max_dep=dep;
    }
    vis[idx]=1;
    for(int i=0;i<v[idx].size();i++) {
        dfs(v[idx][i],dep+1,r_i);
    }
}
void dfs1(int idx){
    if(vis[idx]) return;
    vis[idx]=1;
    for(int i=0;i<v[idx].size();i++) dfs1(v[idx][i]);
}
int main(){
    cin>>n;int v1,v2;
    for(int i=0;i<n-1;i++){
        cin>>v1>>v2;
        v[v1].push_back(v2);
        v[v2].push_back(v1);
    }
    int  flag=0;
    for(int i=1;i<=n;i++){
        if(vis[i])continue;
        flag++;dfs1(i);
    }
    if(flag>1){
        printf("Error: %d components",flag);return 0;
    }
    for(int i=1;i<=n;i++){
        memset(vis,0,sizeof(vis));
        dfs(i,0,i);
    }
    for(set<int>::iterator it=ans[max_dep].begin();it!=ans[max_dep].end();it++) cout<<*it<<endl;
}