@iamtts
2017-03-31T23:30:20.000000Z
字数 911
阅读 798
a不来时: dp[a][0]+=max(dp[b][1],dp[b][0])
a来时 : dp[a][1]=dp[b][0]
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
using namespace std;
#define maxn 6005
int n;
int dp[maxn][2],father[maxn];
void tree_dp(int node)
{
int i;
for(i=1; i<=n; i++)
{
if(father[i] == node)
{
tree_dp(i);
dp[node][1] += dp[i][0];
dp[node][0] +=max(dp[i][1],dp[i][0]);
}
}
}
int main()
{
int i;
int f,c,root;
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
memset(father,0,sizeof(father));
for(i=1; i<=n; i++)
{
scanf("%d",&dp[i][1]);
}
root = 0;
bool beg = 1;
while (scanf("%d %d",&c,&f),c||f)
{
father[c] = f;
if( root == c || beg )
{
root = f;
}
}
while(father[root])
root=father[root];
tree_dp(root);
int imax=max(dp[root][0],dp[root][1]);
printf("%d\n",imax);
}
return 0;
}