1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <bits/stdc++.h> using namespace std; const int N = 1e4 + 10, M = 2 * N;
int n; int head[N], edge[M], ne[M], weight[M], tot = 1; int d1[N], d2[N], p1[N]; int up[N];
void add(int a, int b, int c) { edge[++tot] = b, weight[tot] = c; ne[tot] = head[a], head[a] = tot; }
void dfs_1(int u, int p = -1) { for (int i = head[u]; ~i; i = ne[i]) { int v = edge[i]; if (v == p) continue; dfs_1(v, u); if (d1[v] + weight[i] >= d1[u]) { d2[u] = d1[u]; d1[u] = d1[v] + weight[i]; p1[u] = v; } else if (d1[v] + weight[i] > d2[u]) d2[u] = d1[v] + weight[i]; } }
void dfs_2(int u, int p = -1) { for (int i = head[u]; ~i; i = ne[i]) { int v = edge[i]; if (v == p) continue; if (p1[u] == v) up[v] = max(up[u], d2[u]) + weight[i]; else up[v] = max(up[u], d1[u]) + weight[i]; dfs_2(v, u); } }
int main() { memset(head, -1, sizeof(head)); int n; 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); } dfs_1(1, -1); dfs_2(1, -1); int res = 0x3f3f3f3f; for (int i = 1; i <= n; ++i) res = min(res, max(up[i], d1[i])); cout << res; }
|