第十五章 GRL_5_A:Diameter of a Tree 树的直径

本文介绍了如何求解树的直径问题。首先定义直径为树中两个最远节点之间的距离。接着,提出一种策略:选择一个节点s,找到其最远节点x,再找到x的最远节点y,最后报告x和y之间的距离作为树的直径。文章提供了具体的求解思路,并附带相关问题链接和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

知识点

直径:树的最远结点间的距离

问题链接

GRL_5_A:Diameter of a Tree

问题内容

求出树的直径

思路

1、任选一结点s,求到s最远的结点x
2、求到x最远结点y
报告结点x与结点y的距离,即树的直径

代码

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int maxx = 100010;
const int INF = 1 << 30;

class Edge {
public:
    int t, w;
    Edge() {};
    Edge(int t ,int w):t(t), w(w) {};
};
vector<Edge> G[maxx];
int n, d[maxx];
bool vis[maxx];
int cnt;

void bfs(int s) {
    for (int i = 0; i < n; i++)
        d[i] = INF;
    queue<int> Q;
    Q.push(s);
    d[s] = 0;

    while (!Q.empty()) {
        int u = Q.front(); Q.pop();
        int len = G[u].size();
        for (int i = 0; i < len; i++) {
            Edge e = G[u][i];
            if (d[e.t] == INF) {
                d[e.t] = d[u] + e.w;
                Q.push(e.t);
            }
        }

    }

}

void solve() {
    // 从任选的结点s出发,选择距离s最远的结点tgt
    bfs(0);

    int maxv = 0, tgt = 0;
    for (int i = 0; i < n; i++) {
        if (d[i] == INF)
            continue;
        if (maxv < d[i]) {
            maxv = d[i];
            tgt = i;
        }
    }


    //从tgt出发,求结点tgt到最远结点的距离maxv
    bfs(tgt);
    maxv = 0;
    for (int i = 0; i < n; i++) {
        if (d[i] == INF)
            continue;
        maxv = max(maxv, d[i]);
    }
    printf("%d\n", maxv);
}
int main() {

    int s, t, w;
    scanf("%d", &n);
    for (int i = 0; i < n - 1; i++) {
        scanf("%d %d %d", &s, &t, &w);
        // 无向图
        G[s].push_back(Edge(t, w));
        G[t].push_back(Edge(s, w));
    }
    solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值