Apple Tree
Time limit:1000ms Memory limit:65536k
Total submissions:9069 accepted:3016
Description
Wshxzt is a lovely girl. She likes Apple very much. One day HX takes she to an apple tree. There is N nodes in the tree. Each node has a amount of apples. Wshxzt starts her happy trips 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 many apples she can eat in to the most K steps.
Input
There is several test cases in the input
Each test case contains three parts.
The first part is a numbers N K, whose meanings we have a talked about just now. We denote the nodes by 1 2 ... N. Since It is a tree with each node can reach any and other on only one route. (1<=n<=100, 0<=k<=200)
The second part contains N integers (all integers is 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 is numbers a, A, a, and node B are adjacent, meaning.
Input would 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 11
1 2
3 2
0 1 2
1 2
1 3
Sample Output
11
2
Source
POJ Contest,author:[email protected]
Topic link : http://poj.org/problem?id=2486;
Test Instructions :
A tree, n points (1-n), N-1 Edge, each point has a weight, to start from 1, take the V-step, the maximum can traverse to the weight value;
Ideas :
Tree-shaped DP;
DP[I][J][0/1] means walking J step under the subtree of I (back to I point with 1);
dp[x][J][0]=max (dp[x][J][0],dp[x][j-t][1]+dp[y][t-1][0]);//Back X ( -1); dp[x][J][0]=max (dp[x][J][0],dp[x][j-t][0]+dp[y][t-2][1]);//go back to Y Point-"x point ( -2); dp[x][J][1]=max (dp[x][J][1],dp[x][j-t][1]+dp[y][t-2][1]);//return to X point must return y point (-2)
Code :
#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>#include <vector>#include <queue>using namespace STD;intdp[205][405][2];intN,k; vector<int>lin[205];voidDfsintXintPre) { for(intI=0; I<lin[x].size (); i++) {intY=lin[x][i];if(Y==pre)Continue; DFS (Y,X); for(intj=k;j>=1; j--) for(intt=1; t<=j;t++) {dp[x][j][0]=max (dp[x][j][0],dp[x][j-t][1]+dp[y][t-1][0]); dp[x][j][0]=max (dp[x][j][0],dp[x][j-t][0]+dp[y][t-2][1]); dp[x][j][1]=max (dp[x][j][1],dp[x][j-t][1]+dp[y][t-2][1]); } }}intMain () { while(scanf("%d%d", &n,&k)!=eof) {memset(DP,0,sizeof(DP));intAA,BB; for(intI=1; i<=n;i++) {lin[i].clear ();scanf("%d", &AA); for(intj=0; j<=k;j++) {dp[i][j][0]=dp[i][j][1]=AA; } } for(intI=1; i<n;i++) {scanf("%d%d", &AA,&BB); Lin[aa].push_back (BB); Lin[bb].push_back (AA); } DFS (1,0);printf("%d\n", Max (dp[1][k][0],dp[1][k][1])); }}
[Poj 2486] Apple Tree DP