1. 思路
- 先用DFS遍历一边图,看看有几个连通块:多于1个连通块则输出连通块的数量,一个连通块执行一下步骤。
- 在对每个节点遍历一点,查看每个节点的最大深度
2. 代码
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 11111;
const int INF = 1000000000;
vector<int> G[maxn];
bool vis[maxn] = {false};
void DFS(int u)
{
vis[u] = true;
for (int j = 0; j < G[u].size(); j++)
{
if (vis[G[u][j]] == false)
{
DFS(G[u][j]);
}
}
}
void DFSfordepth(int u, int depth, int& max_depth)
{
if(depth > max_depth)
{
max_depth = depth;
}
vis[u] = true;
for (int j = 0; j < G[u].size(); j++)
{
if (vis[G[u][j]] == false)
{
DFSfordepth(G[u][j], depth+1, max_depth);
}
}
}
int main()
{
int n;
scanf("%d", &n);
int u, v;
for (int i = 0; i < n - 1; i++)
{
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
int block = 0;
for (int i = 1; i <= n; i++)
{
if (vis[i] == false)
{
DFS(i);
block++;
}
}
if (block > 1)
{
printf("Error: %d components", block);
return 0;
}
else
{
int depth_arr[n + 1];
int longest = 0;
for (int query = 1; query <= n; query++)
{
memset(vis, false, sizeof(vis));
int max_depth = 0;
DFSfordepth(query, 1, max_depth);
depth_arr[query] = max_depth;
longest = max(longest, depth_arr[query]);
}
for (int j = 1; j <= n; j++)
{
if (depth_arr[j] == longest)
{
printf("%d\n", j);
}
}
}
return 0;
}