题目描述:
给你一个无权无向的树。编写程序以输出该树中最长路径(从一个节点到另一个节点)的长度。在这种情况下,路径的长度是我们从开始到目的地的遍历边数。
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 10000; // 根据需要调整最大节点数
vector<int> adj[MAXN];
bool visited[MAXN];
int dist[MAXN];
int bfs(int start, int& furthestNode) {
memset(visited, 0, sizeof(visited));
memset(dist, 0, sizeof(dist));
queue<int> q;
q.push(start);
visited[start] = true;
int maxDistance = 0;
furthestNode = start;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (!visited[v]) {
visited[v] = true;
dist[v] = dist[u] + 1;
q.push(v);
if (dist[v] > maxDistance) {
maxDistance = dist[v];
furthestNode = v;
}
}
}
}
return maxDistance;
}
int main() {
int N;
cin >> N;
for (int i = 0; i < N - 1; ++i) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int furthestNode;
// First BFS to find the furthest node from an arbitrary starting point (e.g., 1)
bfs(1, furthestNode);
// Second BFS from the furthest node found to determine the diameter
int diameter = bfs(furthestNode, furthestNode);
cout << diameter << endl;
return 0;
}