FOJ 1615

题目连接: http://acm.fzu.edu.cn/problem.php?pid=1615

树形DP,承上篇,模板题;

代码:

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
const  int  N = 10005;
struct Node
{
       char name[15];
       int father;
       int brother;
       int child;
       int decrese;
       int Invite;
       int Not_Invite;
       int Max_1()
       {
                if(Invite>Not_Invite) return Invite;
                return   Not_Invite;   
       }
       int Max_2()
       {
                if(Invite-decrese>Not_Invite)  return  Invite-decrese;
                return    Not_Invite;            
       }
       int Init()
       {
                father=brother=child=decrese=Not_Invite=0;
       }
}Tree[N];
int search(char str[],int n)
{
       for(int i=1;i<=n;i++)
            if(!strcmp(Tree[i].name,str)) return i;
}
void  dfs(int idx)
{
          int child;
          child=Tree[idx].child;
          while(child)
          {
                     dfs(child);          
                     Tree[idx].Invite+=Tree[child].Max_2();
                     Tree[idx].Not_Invite+=Tree[child].Max_1();
                     child=Tree[child].brother;
          }    
}
int n;
int main()
{
        while(scanf("%d",&n)!=EOF)
        {
             int i,cnt;
             for(i=1;i<=n;i++)
             {
                         scanf("%s",&Tree[i].name);
                         scanf("%d",&Tree[i].Invite);          
                         Tree[i].Init();                                                    
             }      
             char a[15],b[15];
             for(i=1;i<n;i++)
             {
                     scanf("%s",&a);
                     scanf("%s",&b);
                     scanf("%d",&cnt);
                     int idx1=search(a,n);
                     int idx2=search(b,n);
                     Tree[idx2].decrese=cnt; 
                     Tree[idx2].father=idx1;
                     Tree[idx2].brother=Tree[idx1].child;
                     Tree[idx1].child=idx2;
             }
            for(i=1;i<=n;i++)
                     if(!Tree[i].father)
                     {
                              dfs(i);       
                              break;
                     }
             cnt=max(Tree[i].Invite,Tree[i].Not_Invite);
             printf("%d/n",cnt);
        }
        return 0;
}

你可能感兴趣的:(FOJ 1615)