hdu1520 简单树形dp

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<algorithm>
 5 using namespace std;
 6 int son[6005],dp[6005][3],father[6005],f[6005][6005],a[6005];
 7 void dfs(int x)
 8 {
 9     if (son[x]==0){
10         dp[x][0]=0; dp[x][1]=a[x];
11         return;
12     }
13     dp[x][1]=a[x];
14     dp[x][0]=0;
15     for (int i=1;i<=son[x];i++)
16     {
17         dfs(f[x][i]);
18         dp[x][1]+=dp[f[x][i]][0];
19         dp[x][0]+=max(dp[f[x][i]][1],dp[f[x][i]][0]);
20     }
21 }
22 int  main()
23 {
24     int n,i,j,x,y,sum;
25     while (~scanf("%d",&n))
26     {
27         for (i=1;i<=n;i++)
28             scanf("%d",&a[i]);
29         memset(son,0,sizeof(son));
30         memset(father,0,sizeof(father));
31         while (~scanf("%d%d",&x,&y)&&x&&y)
32         {
33             son[y]++;
34             f[y][son[y]]=x;
35             father[x]=y;
36         }
37         for (i=1;i<=n;i++)
38             if (father[i]==0) dfs(i);
39         sum=0;
40         for (i=1;i<=n;i++)
41             if (father[i]==0)
42             sum+=max(dp[i][0],dp[i][1]);
43         printf("%d\n",sum);
44     }
45 }

http://acm.hdu.edu.cn/showproblem.php?pid=1520

posted on 2014-10-30 23:30  xiao_xin  阅读(70)  评论(0编辑  收藏  举报

导航