poj2486 Apple Tree(树形DP,有反回的情况,求最大)........很典型

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 11
1 2
3 2
0 1 2
1 2
1 3

Sample Output

11
2
 
  
#include
int vist[105],node[105][105],len[105],val[105],step;
int dp[2][105][205];//dp[1][p][k]表示用k步(k仅仅只用于以节点p为根的子树,不包含从p的父节点走到p的步数)(最终)人还在节点p(根节点是相对于子节点而言)
int max(int a,int b)
{
    return a>b?a:b;
}
void dfs(int p)
{
    for(int i=0;i<=step;i++)//注意从0开始
    dp[0][p][i]=dp[1][p][i]=val[p];
    vist[p]=1;
    for(int i=1;i<=len[p];i++)
    {
        int son=node[p][i];
        if(vist[son])continue;
        dfs(son);

        for(int s=step;s>=1;s--)//以p为根的子树固定步数s
        for(int st=0;st<=s-1;st++)//子节点(树)的步数st
        {
            if(s-st-2>=0)
           {
               dp[1][p][s]=max(dp[1][p][s],dp[1][p][s-st-2]+dp[1][son][st]);
               dp[0][p][s]=max(dp[0][p][s],dp[0][p][s-(st+2)]+dp[1][son][st]);//(st+2)表示的是能从p到son,并从son到p
           //(这里面减2是为了保证连续性,)遍历了son以前的子节点中其中一个没有反回根节点,但必须保证能从son节点反回根节点p,所以最终没回到p
           }
           dp[0][p][s]=max(dp[0][p][s],dp[1][p][s-st-1]+dp[0][son][st]);//同样要保证连续性,跟上述同理
        }

    }
}
int main()
{
    int n,a,b,max;
    while(scanf("%d%d",&n,&step)>0)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&val[i]);
            len[i]=0,vist[i]=0;
        }
        for(int i=1;i


你可能感兴趣的:(ACM,背包&DP)