这题看见想了几分钟。。。别的甲级题目都是看见都能做的裸题,这道题先要判断给出的图是不是树,因为题目条件,n个点,n - 1条边,要么是树,要么是连通分量大于1的图,不可能是一连通分量个数为一的图,所以先DFS一次,看看有几个连通分量,然后再对是树的情况,DFS遍历,求最大深度点。可能我这个方法普通,耗时最长的一个点1000ms.
#include <bits/stdc++.h>
using namespace std;
int n, c1, c2, ans = 0, rec[10010], tempmax, Max = -1;
bool visit[10010] = {};
vector<int> v[10010];
void DFS(int s, int depth)
{
visit[s] = true;
if(depth > tempmax) tempmax = depth;
for(int i = 0; i < v[s].size(); i++){
if(!visit[v[s][i]]) DFS(v[s][i], depth + 1);
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n - 1; i++){
scanf("%d%d", &c1, &c2);
v[c1].push_back(c2), v[c2].push_back(c1);
}
for(int i = 1; i <= n; i++){
if(!visit[i]){
DFS(i, 0);
ans++;
}
}
if(ans > 1) printf("Error: %d components", ans);
else{
for(int i = 1; i <= n; i++){
fill(visit, visit + 10010, false);
tempmax = -1;
DFS(i, 0);
rec[i] = tempmax;
if(tempmax > Max) Max = tempmax;
}
for(int i = 1; i <= n; i++){
if(rec[i] == Max) printf("%d\n", i);
}
}
return 0;
}