现在的位置: 首页 > 综合 > 正文

hdu1520

2013年10月07日 ⁄ 综合 ⁄ 共 812字 ⁄ 字号 评论关闭

/*
分析:
    树形DP果题。

                     2012-09-05
*/

#include"stdio.h"
#include"string.h"

struct A
{
	int from;
	int to;
	int next;
}eage[10011];
int tot;
int head[6011];
int base[6011];
int hash[6011];
int dp[6011][2];

int MAX(int a,int b)
{
	return a>b?a:b;
}
void add(int a,int b)
{
	eage[tot].from=a;
	eage[tot].to=b;
	eage[tot].next=head[a];
	head[a]=tot++;
}
void dfs(int root)
{
	int j,u;
	dp[root][0]=0;
	dp[root][1]=base[root];
	for(j=head[root];j!=-1;j=eage[j].next)
	{
		u=eage[j].to;
		dfs(u);
		dp[root][0]+=MAX(dp[u][0],dp[u][1]);
		dp[root][1]+=dp[u][0];
	}
}

int main()
{
	int n;
	int i;
	int a,b;
	int t;
	while(scanf("%d",&n)!=-1)
	{
		for(i=1;i<=n;i++)	scanf("%d",&base[i]);

		tot=0;
		memset(head,-1,sizeof(head));
		memset(hash,0,sizeof(hash));
		while(scanf("%d%d",&a,&b),a||b)	{hash[a]=1;add(b,a);}

		for(i=1;i<=n;i++)	if(!hash[i])	{t=i;break;}
		memset(dp,0,sizeof(dp));
		dfs(t);

		printf("%d\n",MAX(dp[t][0],dp[t][1]));
	}
	return 0;
}

抱歉!评论已关闭.