hdu 1054 树形dp

/*
    【题意】 给定一棵树,标记一节点,则与该节点所连的边都被标记,问最少需要标记多少个节点使得所有边都被标记;
     或者说给定一个树型城堡,在交叉路口放一个士兵,则与该路口相连的路都被守住,
     问最少需要派遣多少个士兵来守住这个城堡
     
     dp[father].yes= ( min(dp[child].yes,dp[child].no) 之和)
     dp[father].yes=( min(dp[child].yes,dp[child].no) 之和)

*/
#include<stdio.h>
#include<string.h>

struct node
{
  int father,brother,child;
  int yes,no;
  
  void init()
  {
       father=brother=child=0;
       yes=1;
       no=0;       
  }
}t[1505];

bool use[1505];
int min(int x,int y)
{
    if(x<y) return x;
    return y;
}

void dfs(int root)
{
   int child=t[root].child;
   while(child)
   {
         dfs(child);
         t[root].yes+=min(t[child].yes,t[child].no);
         t[root].no+=t[child].yes;
         child=t[child].brother;         
   }
}
/*
void dfs(int root)
{
  int child=t[root].child;
   while(child)
   {
         dfs(child);
         printf("root%d %d",root,child);
         child=t[child].brother;         
   }
}*/


int  main()
{
     int n,Root,root,cnt,j;
    while(scanf("%d",&n)!=EOF)
    {
      memset(use,0,sizeof(use));
      
      //int Root;
      
      for(int i=1;i<=n;i++)
      {
           scanf("%d:(%d)",&root,&cnt),root++;
           if(i==1) Root=root;
           
           if(!use[root])
           {
             t[root].init();
             use[root]=1;
           }
           
           while(cnt--)
           {
              scanf("%d",&j),j++;
              if(!use[j])
              {
                   t[j].init();
                   use[j]=1;
               }
               t[j].brother=t[root].child;
               t[j].father=root;
               t[root].child=j;
            }
        }
      
       dfs(Root); 
       
       printf("%d\n",min(t[Root].no,t[Root].yes));
                              
                              
    }   
     
     
 return 0;     
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值