输入样例#1: 复制
5 2 1 3 1 1 4 10 2 3 20 3 5 20
输出样例#1: 复制
21
链式前向星存图 在q范围内计算左右儿子的苹果和
#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
int dp[maxn][maxn];
int head[maxn];
int son[maxn];
int n, q;
int tot;
struct node{
int to;
int apple;
int next;
node() {}
node(int a, int b, int c) : to(a), apple(b), next(c) {}
} edge[maxn];
void init(){
tot = 0;
memset(head, -1, sizeof(head));
memset(dp, 0, sizeof(dp));
}
void edgeadd(int a, int b, int apple){
edge[tot] = node(a, apple, head[b]);
head[b] = tot++;
edge[tot] = node(b, apple, head[a]);
head[a] = tot++;
}
void dfs(int rt, int f){
for(int i = head[rt]; i != -1; i = edge[i].next){
int v = edge[i].to;
//cout << v << endl;
if(v == f)
continue;
dfs(v, rt);
son[rt] += son[v] + 1;//计算子节点数
for(int j = min(son[rt], q); j >= 1; j--){
for(int k = j; k >= 1; k--){
dp[rt][j] = max(dp[rt][j], edge[i].apple + dp[v][k - 1] + dp[rt][j - k]);
//cout << dp[rt][j] <<endl;
}
}
}
}
int main(){
cin >> n >> q;
int a, b, c;
init();
for(int i = 0; i < n - 1; i++){
cin >> a >> b >> c;
edgeadd(a, b, c);
}
dfs(1, -1);
cout << dp[1][q] << endl;
}