1380 没有上司的舞会
一道树形DP。
气死我了。一开始以为是二叉树,结果拿了90分。看到数据。。。只是一棵树而已。。。难度增加。
上网看看有没有好的思路,都是C++,C++就算了吧,还都用STL,让我C情何以堪。
(甚至有pascal都没有C)
为了挽留C的面子,我来一份C的程序。
#include<stdio.h>
typedef struct edge{
int next;
int last;
int after;
}E;
int N;
E a[6005];
int w[6005];
int dp[6005][2];
int max(int a,int b)
{
return a>b?a:b;
}
int dfs(int num)
{
int temp;
dp[num][1]+=w[num];
if(a[num].after==0)
return 0;
if(a[num].after!=0)
dfs(a[num].after);//对所有存在根节点的点深搜
temp=a[num].after;
dp[num][1]+=dp[temp][0];
dp[num][0]+=max(dp[temp][0],dp[temp][1]);
temp=a[a[num].after].next;
while(temp!=0)
{
dfs(temp);//它的兄弟节点也要深搜
dp[num][1]+=dp[temp][0];
dp[num][0]+=max(dp[temp][0],dp[temp][1]);
temp=a[temp].next;
}
return 0;
}
int main()
{
int i;
int K,L;
int P;
scanf("%d",&N);
for(i=1;i<=N;i++)
scanf("%d",&w[i]);
for(i=1;i<=N;i++)
{
a[i].next=0;
a[i].after=0;
}
for(i=1;i<=N;i++)
{
scanf("%d %d",&L,&K);
if(L!=0&&K!=0)
{
a[L].next=a[K].after;
a[K].after=L;
a[L].last=K;
}
}
P=1;
while(a[P].last!=0)
P=a[P].last;
a[0].after=P;
dfs(P);
//for(i=1;i<=N;i++)
//printf("%d %d\n",dp[i][1],dp[i][0]);
printf("%d",max(dp[P][1],dp[P][0]));
return 0;
}