URAL 1018 Binary Apple Tree 簡單樹形揹包
阿新 • • 發佈:2019-02-01
Description
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
2 5 \ / 3 4 \ / 1 |
Input
Output
Sample Input
input | output |
---|---|
5 2 1 3 1 1 4 10 2 3 20 3 5 20 |
21 |
題意:一顆n個節點的樹,去掉一些邊,使得剩下m條邊,使得邊權和最大,1為根節點,必須保留。
簡單樹形揹包,先dfs出以各個節點為根的子樹的大小,然後揹包求最大值。
程式碼:
/* ***********************************************
Author :xianxingwuguan
Created Time :2014-2-11 2:29:40
File Name :4.cpp
************************************************ */
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <time.h>
#include <math.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
typedef long long ll;
const int maxn=130;
int head[maxn],tol,dp[maxn][maxn],size[maxn],m,n;
struct node{
int next,to,val;
node(){};
node(int _next,int _to,int _val):next(_next),to(_to),val(_val){}
}edge[10*maxn*maxn];
void add(int u,int v,int w){
edge[tol]=node(head[u],v,w);
head[u]=tol++;
}
void dfs(int u,int fa){
size[u]=1;
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(v==fa)continue;
dfs(v,u);
size[u]+=size[v];
}
for(int i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(v==fa)continue;
for(int j=size[u];j>1;j--)
for(int k=1;k<j;k++)
dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]+edge[i].val);
}
}
int main()
{
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
while(~scanf("%d%d",&n,&m)){
memset(head,-1,sizeof(head));tol=0;
for(int i=1;i<n;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
dfs(1,-1);
printf("%d\n",dp[1][m+1]);
}
return 0;
}