Skip to content

AcWing 1072. 树的最长路径

问题描述

link

分析

参考代码

cpp
#include <bits/stdc++.h>
using namespace std;

int head[10005], e[20005], w[20005], ne[20005], tot;
int n, ans, d[10005], st[10005];

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

void dp(int x) {
    st[x] = true;
    for (int i = head[x]; i; i = ne[i]) {
        int y = e[i];
        if (st[y]) continue;
        dp(y);
        ans = max(ans, d[x] + d[y] + w[i]);
        d[x] = max(d[x], d[y] + w[i]);
    }
}

int main() {
    cin >> n;
    for (int i = 1; i < n; i++) {
        int a, b, c; cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }

    dp(1);

    cout << ans << endl;

    return 0;
}