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
| #include <bits/stdc++.h> using namespace std; const int N = 101, M = 202; int u, v, ww, h[N], e[M], ne[M], w[M], idx; int n, t; int dp[N][N]; void add(int u, int v, int ww) { e[++idx] = v, w[idx] = ww, ne[idx] = h[u], h[u] = idx; } int dfs(int u, int f) { int sum = 0; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v == f) continue; int s = dfs(v, u); sum += s + 1; for (int j = min(sum, t); j; --j) for (int k = min(s, j - 1); k >= 0; --k) dp[u][j] = max(dp[u][j], dp[v][k] + dp[u][j - k - 1] + w[i]); } return sum; } int main() { scanf("%d%d", &n, &t); for (int i = 1; i < n; ++i) { scanf("%d%d%d", &u, &v, &ww); add(u, v, ww); add(v, u, ww); } dfs(1, 0); printf("%d\n", dp[1][t]); return 0; }
|