思路:
树形dp + 分组背包dp。
参考https://www.cnblogs.com/kuangbin/archive/2012/08/29/2661928.html
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef pair<int, int> pii; 4 5 const int MAXN = 100005; 6 vector<pii> G[MAXN]; 7 int dp[MAXN][11], n, s, k; 8 9 void dfs(int u, int f) 10 { 11 for (int i = 0; i < G[u].size(); i++) 12 { 13 int v = G[u][i].first, w = G[u][i].second; 14 if (v == f) continue; 15 dfs(v, u); 16 for (int j = k; j >= 0; j--) 17 { 18 dp[u][j] += dp[v][0] + 2 * w; 19 for (int l = 1; l <= j; l++) 20 { 21 dp[u][j] = min(dp[u][j], dp[v][l] + l * w + dp[u][j - l]); 22 } 23 } 24 } 25 } 26 27 int main() 28 { 29 while (scanf("%d %d %d", &n, &s, &k) != EOF) 30 { 31 memset(dp, 0, sizeof dp); 32 for (int i = 1; i <= n; i++) G[i].clear(); 33 int a, b, w; 34 for (int i = 0; i < n - 1; i++) 35 { 36 scanf("%d %d %d", &a, &b, &w); 37 G[a].push_back(pii(b, w)); 38 G[b].push_back(pii(a, w)); 39 } 40 dfs(s, 0); 41 printf("%d ", dp[s][k]); 42 } 43 return 0; 44 }