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
| #include<iostream> #include<algorithm> #include<cstdio>
using namespace std;
int n, rem, tot; int f[105][105], sz[105], head[105]; struct edge { int to, nxt, w; } e[105 << 1];
void add(int u, int v, int w) { e[++tot] = {v, head[u], w}; head[u] = tot; }
void dfs(int u, int fa) { for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (v == fa) continue; dfs(v, u); sz[u] += sz[v] + 1; for (int j = min(rem, sz[u]); j >= 0; --j) { for (int k = min(j - 1, sz[v]); k >= 0; --k) { f[u][j] = max(f[u][j], f[u][j - k - 1] + f[v][k] + e[i].w); } } } }
int main(int argc, char *argv[]) { ios::sync_with_stdio(false); cin >> n >> rem; int u, v, w; for (int i = 0; i < n - 1; ++i) { cin >> u >> v >> w; add(u, v, w); add(v, u, w); } dfs(1, -1); cout << f[1][min(sz[1], rem)] << endl; return 0; }
|