前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >树的直径

树的直径

作者头像
灯珑LoGin
发布2022-10-31 13:13:09
2890
发布2022-10-31 13:13:09
举报
文章被收录于专栏:龙进的专栏

求一棵树的直径的方法就是,从一个顶点出发,找到离它最远的顶点s,然后从顶点s出发,找离他最远的节点t.那么,s、t之间的距离就是树的直径。

对于加权无向树来说,树的直径就是s、t之间的路径上的边的权值相加。

题目:GRL_5_A

AC代码:

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#include <algorithm>
using namespace std;

#define MAXN 100005

struct edge
{
    int from, to, weight;
};

vector<edge> vec[MAXN];
int n;

bool cmp(const int &a, const int &b)
{
    return a > b;
}

int d[MAXN];

void bfs(int r)
{
    queue<int> q;
    bool vis[MAXN] = {false};
    q.push(r);
    vis[r] = true;

    memset(d, 0, sizeof(d));
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        for (edge e : vec[u])
        {
            if (!vis[e.to])
            {
                d[e.to] = d[u] + e.weight;
                q.push(e.to);
                vis[e.to] = true;
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> n;

    int s, t, w;
    edge tmp1, tmp2;
    for (int i = 0; i < n - 1; ++i)
    {
        cin >> s >> t >> w;
        tmp1.from = s;
        tmp1.to = t;
        tmp1.weight = tmp2.weight = w;
        tmp2.from = t;
        tmp2.to = s;
        vec[s].push_back(tmp1);
        vec[t].push_back(tmp2);
    }

    bfs(0);

    int m = -1, v;
    for (int i = 0; i < n; ++i)
        if (d[i] > m)
        {
            m = d[i];
            v = i;
        }

    bfs(v);

    sort(d, d + n, cmp);

    cout << d[0] << endl;
}

转载请注明出处:https://www.longjin666.top/?p=767

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021年1月31日2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档