poj2486 Apple Tree 题解

来源:互联网 发布:php 一键生成工具 编辑:程序博客网 时间:2024/05/22 11:00
Wshxzt is a lovely girl. She likes apple very much. One day HX takes her to an apple tree. There are N nodes in the tree. Each node has an amount of apples. Wshxzt starts her happy trip at one node. She can eat up all the apples in the nodes she reaches. HX is a kind guy. He knows that eating too many can make the lovely girl become fat. So he doesn’t allow Wshxzt to go more than K steps in the tree. It costs one step when she goes from one node to another adjacent node. Wshxzt likes apple very much. So she wants to eat as many as she can. Can you tell how many apples she can eat in at most K steps.
Input
There are several test cases in the input 
Each test case contains three parts. 
The first part is two numbers N K, whose meanings we have talked about just now. We denote the nodes by 1 2 ... N. Since it is a tree, each node can reach any other in only one route. (1<=N<=100, 0<=K<=200) 
The second part contains N integers (All integers are nonnegative and not bigger than 1000). The ith number is the amount of apples in Node i. 
The third part contains N-1 line. There are two numbers A,B in each line, meaning that Node A and Node B are adjacent. 
Input will be ended by the end of file. 

Note: Wshxzt starts at Node 1.
Output
For each test case, output the maximal numbers of apples Wshxzt can eat at a line.
Sample Input
2 1 0 111 23 20 1 21 21 3
Sample Output
11

2

#include<stdio.h>#include<string.h>int a[201],b[201];struct Edge{int to,next,len;//链表存边};Edge edge[401];int head[201],idx,n,m;int f[2][201][201];int max(int a,int b){if(a>b)return a;return b;}void dfs(int from,int p){for(int i=head[p];i;i=edge[i].next){if(edge[i].to!=from){dfs(p,edge[i].to);for(int j=m;j>=1;j--)for(int k=1;k<=j;k++){f[0][p][j]=max(max(f[0][p][j],f[1][p][j-k]+f[0][edge[i].to][k-1]),(f[0][p][j-k]+f[1][edge[i].to][k-2]));f[1][p][j]=max(f[1][p][j],f[1][p][j-k]+f[1][edge[i].to][k-2]);}//dp方程}}}void addedge(int a,int b){++idx;edge[idx].to=b;edge[idx].next=head[a];head[a]=idx;}int main(){int c,b;while(scanf("%d%d",&n,&m)==2){idx=0;memset(f,0,sizeof(f));for(int i=1;i<=n;i++)scanf("%d",&a[i]),head[i]=0;for(int i=1;i<=n;i++){for(int j=0;j<=m;j++)f[0][i][j]=f[1][i][j]=a[i];}for(int i=1;i<n;i++){scanf("%d",&c);scanf("%d",&b);addedge(c,b);addedge(b,c);}dfs(0,1);int ans;ans=max(f[0][1][m],f[1][1][m]);printf("%d\n",ans);}}

原创粉丝点击