1018. Binary Apple Tree
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
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.
Input
First line of input contains two numbers:
N and
Q (
2 ≤
N ≤ 100;
1 ≤
Q ≤
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
Output should contain the only number — amount of apples that can be preserved. And don't forget to preserve tree's root ;-)
Sample
input | output |
---|---|
5 2 1 3 1 1 4 10 2 3 20 3 5 20 | 21 |
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=103;
typedef struct
{
int lc,rc;
int val;
} Node;
Node tree[MAXN];
int m,n;
int arr[MAXN][MAXN];
int f[MAXN][MAXN];
int vis[MAXN];
void Create(int root)//建树
{
vis[root]=1;
for(int i=1; i<=m; i++)
{
if(!vis[i]&&arr[root][i])
{
if(!tree[root].lc)
tree[root].lc=i;
else
tree[root].rc=i;
tree[i].val=arr[root][i];
Create(i);
}
}
}
int TreeDP(int root,int e)/**树形DP**/
{
if(!root||!e)
return 0;
if(f[root][e])
return f[root][e];
int maxx=0;
int l,r;
for(int i=0; i<e; i++)
{
l=TreeDP(tree[root].lc,i);//左子树要留下i根枝条
r=TreeDP(tree[root].rc,e-i-1);//右子树要留下e-i-1
maxx=max(l+r,maxx);
}
f[root][e]=maxx+tree[root].val;//根要留下一根枝条
return f[root][e];
}
int main()
{
memset(arr,0,sizeof(arr));
memset(vis,0,sizeof(vis));
memset(tree,0,sizeof(tree));
scanf("%d %d",&m,&n);
int l,f,v;
for(int i=1; i<m; i++)
{
scanf("%d %d %d",&l,&f,&v);
arr[l][f]=arr[f][l]=v;
}
Create(1);
printf("%d\n",TreeDP(1,++n));
return 0;
}