POJ 2496 Apple Tree

来源:互联网 发布:《南风知我意》琰阙 编辑:程序博客网 时间:2024/06/06 09:59

Description

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

112

Source

POJ Contest,Author:magicpig@ZSU

哈哈,双倍经验,与上一个题相同,注意多组数据。

#include<iostream>#include<cstring>#include<cstdio>using namespace std;const int N=105;const int M=205;int n,m,cnt,hd[N],w[N],f[N][M][2];struct edge{int nxt,to;}v[2*N];void addedge(int x,int y){++cnt;v[cnt].nxt=hd[x];hd[x]=cnt;v[cnt].to=y;}void dp(int u,int fa){for(int i=0;i<=m;i++)f[u][i][0]=f[u][i][1]=w[u];for(int i=hd[u];i;i=v[i].nxt)if(v[i].to!=fa){dp(v[i].to,u);for(int j=m;j>=1;j--)for(int k=1;k<=j;k++){if(k>=2){f[u][j][1]=max(f[u][j][1],f[u][j-k][1]+f[v[i].to][k-2][1]);f[u][j][0]=max(f[u][j][0],f[u][j-k][0]+f[v[i].to][k-2][1]);}f[u][j][0]=max(f[u][j][0],f[u][j-k][1]+f[v[i].to][k-1][0]);}}}int main(){while(~scanf("%d%d",&n,&m)){cnt=0;memset(hd,0,sizeof(hd));for(int i=1;i<=n;i++)scanf("%d",&w[i]);for(int i=1;i<=n-1;i++){int x,y;scanf("%d%d",&x,&y);addedge(x,y),addedge(y,x);}dp(1,-1);printf("%d\n",f[1][m][0]);}return 0;}

0 0