P2015 二叉苹果树 树形dp
作者:
多米尼克領主的致意
,
2024-06-04 17:45:44
,
所有人可见
,
阅读 2
code:
#include <bits/stdc++.h>
using namespace std;
const int N = 210;
int n, q;
struct node{
int v, w;
node(int x, int y) {v = x, w = y;}
};
vector<node>e[N];
int f[N][N], sum[N];
void dfs(int u, int fa){
for(int i = 0;i < e[u].size();i++){
// cout << 1 << endl;
int v = e[u][i].v, w = e[u][i].w;
if(v == fa)continue;
dfs(v, u);
sum[u] += sum[v] + 1;
for(int j = min(q, sum[u]);j >= 1;j--){
// cout << 1 << endl;
for(int k = min(j - 1, sum[v]);k >= 0;k--){
// cout << 1 << endl;
f[u][j] = max(f[u][j], f[u][j - k - 1] + f[v][k] + w);
//状态转移 关键一步
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> q;
for(int i = 1;i <= n - 1;i++){
int x, y, w;
cin >> x >> y >> w;
e[x].push_back(node(y, w));
e[y].push_back(node(x, w));
}
// cout << e[1][0].v << endl;
dfs(1, 0);
cout << f[1][q];
return 0;
}