[AcWing 1072] 树的最长路径

image
image


点击查看代码
#include<iostream>
#include<cstring>

using namespace std;

typedef long long LL;

const int N = 1e6 + 10;

int n;
int h[N], e[N], ne[N], w[N], idx;
int res;

void add(int a, int b, int c)
{
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx ++;
}

int dfs(int u, int father)
{
    int d1 = 0, d2 = 0;
    for (int i = h[u]; i != -1; i = ne[i]) {
        int j = e[i];
        if (j == father)
            continue;
        int d = dfs(j, u) + w[i];
        if (d > d1)
            d2 = d1, d1 = d;
        else
            d2 = max(d2, d);
    }
    res = max(res, d1 + d2);
    return d1;
}

int main()
{
    cin >> n;
    memset(h, -1, sizeof h);
    for (int i = 0; i < n - 1; i ++) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    dfs(1, -1);
    cout << res << endl;
    return 0;
}

  1. 树形 \(dp\)
    由于是无向图,可以以任意点作为树的根节点,向下遍历,每次记录以此节点作为端点的路径的最大值和次大值,对于每一个点,所属的最长路径应为最大值和次大值之和
posted @ 2022-07-11 21:24  wKingYu  阅读(42)  评论(0)    收藏  举报