遍历图中的每个节点,每次都将当前节点作为根节点求当前最大深度。
#include <bits/stdc++.h>
using namespace std;
const int N = 10010, M = 2 * N;
int n;
int e[M], ne[M], h[N], idx;
int f[N];
int maxDepth = -1;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int find(int x)
{
if(f[x] != x) f[x] = find(f[x]);
return f[x];
}
int dfs(int u, int father)
{
int depth = 0;
for(int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if(father == j) continue;
depth = max(depth, dfs(j, u) + 1);
}
return depth;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for(int i = 1; i <= n; i++) f[i] = i;
int k = n;
for(int i = 0; i < n; i++)
{
int a, b;
cin >> a >> b;
add(a, b); add(b, a);
if(find(a) != find(b))
{
k --;
f[find(b)] = find(a);
}
}
if(k != 1) printf("Error: %d components", k);
else
{
vector<int> nodes;
for(int i = 1; i <= n; i++)
{
int depth = dfs(i, -1);
if(depth > maxDepth)
{
nodes.clear();
nodes.push_back(i);
maxDepth = depth;
}
else if(depth == maxDepth) nodes.push_back(i);
}
for(auto n : nodes) cout << n << endl;
}
}