hdu 1520 没有上司的晚会

树形dp入门题

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

Attention:

hdu上每个输入都有多组数据

可能有既没有上司也没有下属的孤点

 

 1 #include<cstdio>
 2 #include<cstring>
 3 int n,i,j,f[6010],fen[6010],l,k,ans=0,top=0;
 4 int a[6010],b[6010],ok[6010];
 5 struct node{
 6     int v;
 7     node *next;
 8 };
 9 node *g[6010],*p;
10 void add(int u,int v)
11 {
12     p=new(node);
13     p->v=v;
14     p->next=g[u];
15     g[u]=p;
16 }
17 int dui[6010],h,t;
18 int max(int a,int b)
19 {
20     if (a>b) return a;else return b;
21 }
22 int main()
23 {
24     while (scanf("%d",&n)!=EOF)
25     {
26         ans=0;
27         memset(a,0,sizeof(a));
28         memset(b,0,sizeof(b));
29         memset(ok,0,sizeof(ok));
30         memset(f,0,sizeof(f));
31         for (i=1;i<=n;i++) g[i]=NULL;
32         for (i=1;i<=n;i++) scanf("%d",&fen[i]);
33         if (n==1) {printf("%d\n",fen[1]); return 0;}
34         while (scanf("%d%d",&l,&k))
35         {
36             if (l+k==0) break;
37             if (ok[k]==0) ok[k]=3;
38             if (ok[k]==1) ok[k]=2;
39             if (ok[l]==0) ok[l]=1;
40             if (ok[l]==3) ok[l]=2;
41             f[l]=k; add(k,l);
42         }
43         for (i=1;i<=n;i++)
44         {
45             if (ok[i]==0) ans+=fen[i];
46             if (ok[i]==1) {a[i]=fen[i]; b[i]=0;}
47             if (ok[i]==2) a[i]=fen[i];
48             if (ok[i]==3) {a[i]=fen[i]; top=i;}
49         }
50         
51         dui[1]=top; h=0; t=1;
52         for (;h!=t;)
53         {
54             h++;
55             p=g[dui[h]];
56             while (p!=NULL)
57             {
58                 dui[++t]=p->v;
59                 p=p->next;
60             }
61         }
62         
63         for (i=t;i>1;i--)
64         {
65             int tmp=dui[i];
66             a[f[tmp]]+=b[tmp];                //a[i]:i来时子树i的氛围值最大值
67             b[f[tmp]]+=max(a[tmp],b[tmp]);    //b[i]:i不来时子树i的氛围值最大值
68         }
69         printf("%d\n",ans+max(a[top],b[top]));
70     }
71 }

 

posted @ 2015-08-14 16:10  Donnie_Darko  阅读(188)  评论(0编辑  收藏  举报