hdu 1520 Anniversary party(树形dp)

本文介绍了一种基于递归实现的树形动态规划算法,通过遍历树结构并计算每个节点的最大收益来解决最优选择问题。文章详细展示了算法的具体实现过程,包括初始化节点属性、递归遍历子树及更新父节点的收益等关键步骤。
/*
   dp[falther].have += dp[child].nothave;
   dp[falther].nothave += max(dp[child].have,dp[child].nothave);
*/


#include <stdio.h>

int max(int x,int y)
{
  if(x>y) return x;
  return y;    
}

struct node
{
  
    int father;
    int child;
    int brother;
    int Hpriority;
    int Npriority;
    
    void init()
    {
       father = child = brother = Npriority = 0;
    }
    
    int Max()
    {
       return max(Hpriority,Npriority);    
    }
}tree[6000+100];


void dfs(int index)
{
   int child=tree[index].child;
   while(child)
   {
       dfs(child);
       
       tree[index].Hpriority += tree[child].Npriority;
       
       tree[index].Npriority += tree[child].Max();
                 
       child =  tree[child].brother;       
   }     
     
}

int main()
{
    int n;
  while(scanf("%d",&n)==1)
  {
                     
     for(int i=1;i<=n;i++)
     {
        tree[i].init(); 
        scanf("%d",&tree[i].Hpriority);
     }
     int x,y;                     
     while(scanf("%d%d",&x,&y) && x+y)
     {
        tree[x].father=y;
        tree[x].brother=tree[y].child;
        tree[y].child=x;
     }
     
     for(int i=1;i<=n;i++)
     {
          if( !tree[i].father)
          {
             dfs(i);
             printf("%d\n",tree[i].Max());
             break;
          }   
     }
  }
    
  return 0;    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值