## Binary Apple Tree

### 题目描述

Let's imagine how apple tree looks in binary computer world. You're right, it looks just like a binary tree, i.e. any biparous branch splits up to exactly two new branches. We will enumerate by integers the root of binary apple tree, points of branching and the ends of twigs. This way we may distinguish different branches by their ending points. We will assume that root of tree always is numbered by $1$ and all numbers used for enumerating are numbered in range from $1$ to $N$, where $N$ is the total number of all enumerated points. For instance in the picture below $N$ is equal to $5$. Here is an example of an enumerated tree with four branches:

2   5
\ /
3   4
\ /
1

As you may know it's not convenient to pick an apples from a tree when there are too much of branches. That's why some of them should be removed from a tree. But you are interested in removing branches in the way of minimal loss of apples. So your are given amounts of apples on a branches and amount of branches that should be preserved. Your task is to determine how many apples can remain on a tree after removing of excessive branches.

### 输入格式

First line of input contains two numbers: $N$ and $Q$ ($2 \le N \le 100$;$1 \le Q \le N-1$).$N$ denotes the number of enumerated points in a tree. $Q$ denotes amount of branches that should be preserved. Next $N-1$ lines contains descriptions of branches. Each description consists of a three integer numbers divided by spaces. The first two of them define branch by it's ending points. The third number defines the number of apples on this branch. You may assume that no branch contains more than $30000$ apples.

### 输出格式

Output should contain the only number — amount of apples that can be preserved. And don't forget to preserve tree's root ;-)

### 样例输入

5 2
1 3 1
1 4 10
2 3 20
3 5 20


### 样例输出

21


## 题解

$dp[i][j]$表示以$i$为根，保留$j$条边最大的权值之和。

$dp[u][i]=max$($dp[u][i],dp[u][i-k-1]+dp[son][k]$)
$dp[u]=val[u][fa]$

#include<bits/stdc++.h>
using namespace std;
int n,q;
int u,v,w;
struct aa{
int to,nxt,v;
}p;
int h,len=1;
void add(int u,int v,int w){
p[++len].to=v;
p[len].v=w;
p[len].nxt=h[u];
h[u]=len;
}
int ss;
int dp;
void dfs(int u,int fa,int us){
ss[u]=0;
for(int j=h[u];j;j=p[j].nxt){
if(p[j].to==fa) continue;
dfs(p[j].to,u,p[j].v);
ss[u]+=1+ss[p[j].to];//记录以u为根的子树的节点数
}
dp[u]=us;//别忘了u节点和父亲的边
for(int j=h[u];j;j=p[j].nxt){
if(p[j].to==fa) continue;
for(int i=q;i>=1;i--){//从大到小枚举防止重复计算
for(int o=0;i-o-1>=0 && o<=ss[p[j].to];o++){
dp[u][i]=max(dp[u][i],dp[u][i-o-1]+dp[p[j].to][o]);
}
}
}
}
int main(){
scanf("%d%d",&n,&q);
for(int j=1;j<n;j++){
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
dfs(1,0,0);
printf("%d",dp[q]);
return 0;
}