//树形DP,递归调用,从叶子节点开始DP;
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#define maxn 10000
using namespace std;
int father[maxn];
bool vis[maxn];
int n;
int dp[maxn][2];
void T_dp(int node)
{
vis[node]=1;
for(int i=1;i<=n;i++)
{
if(father[i]==node && !vis[i])
{
T_dp(i);
dp[node][1]+=dp[i][0];
dp[node][0]+=max(dp[i][0],dp[i][1]);
}
}
}
int main()
{
int x,y;
while(scanf("%d",&n)!=EOF)
{
memset(father,0,sizeof(father));
for(int i=1;i<=n;i++)
scanf("%d",&dp[i][1]);
while(1)
{
scanf("%d%d",&x,&y);
if(x==0&&y==0)
break;
father[x]=y;
}
int root=1;
while(father[root])
{
root=father[root];
}
memset(vis,false,sizeof(vis));
T_dp(root);
cout<<max(dp[root][0],dp[root][1])<<endl;
}
}
poj 2342 树形DP
最新推荐文章于 2018-08-17 07:22:55 发布