树的直径算法(dfs)

1.什么是树的直径?

树的直径是一颗树中任意两点最长的距离

2.如何求树的直径?

(1).任意找一点x,并求得树上任意一点到x的距离存到数组dist中

(2).找到距离x最长的点y并以点y为起点找到树中距离y最远的点z,则z-y长度就是树的直径

3.证明y一定是某一直径的端点

acwing1207

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n;
struct Edge
{
    int id, w;
};
vector<Edge> h[N];
int dist[N];

void dfs(int u, int father, int distance)//
{
    dist[u] = distance;

    for (auto node : h[u])
        if (node.id != father)
            dfs(node.id, u, distance + node.w);
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n - 1; i ++ )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        h[a].push_back({b, c});
        h[b].push_back({a, c});
    }

    dfs(1, -1, 0);

    int u = 1;
    for (int i = 1; i <= n; i ++ )
        if (dist[i] > dist[u])
            u = i;

    dfs(u, -1, 0);

    for (int i = 1; i <= n; i ++ )
        if (dist[i] > dist[u])
            u = i;

    int s = dist[u];

    printf("%lld\n", s * 10 + s * (s + 1ll) / 2);

    return 0;
}


版权声明:本文为m0_56250941原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。