【模板】树的直径 ,C++代码实现

题目描述:

给你一个无权无向的树。编写程序以输出该树中最长路径(从一个节点到另一个节点)的长度。在这种情况下,路径的长度是我们从开始到目的地的遍历边数。

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值