树的最长路径

https://www.acwing.com/problem/content/1074/

  • \(对于每个节点, 得到其最长路径和次长路径\ d_1 和\ d_2\)
  • \(最长路径\ d = d_1 + d_2\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi firt
#define se second
#define inf 0x3f3f3f3f
const int N = 1e5 + 10, M = N * 2;
int n;
int h[N], e[M], w[M], ne[M], idx;
int ans;

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

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

int main() {
    IO;
    memset(h, -1, sizeof h);
    cin >> n;
    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 << ans << '\n';
    return 0;
}


posted @ 2021-01-30 23:22  phr2000  阅读(78)  评论(0编辑  收藏  举报