树形DP
dp[i][1/0]
表示 以
i
为根的子树 选/不选
dp[i][1]=(∑dp[son][0])+w[i]
dp[i][0]=∑max(dp[son][1],dp[son][0])
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <iostream>
#include <algorithm>
template<class Num>void read(Num &x)
{
char c; int flag = 1;
while((c = getchar()) < '0' || c > '9')
if(c == '-') flag *= -1;
x = c - '0';
while((c = getchar()) >= '0' && c <= '9')
x = (x<<3) + (x<<1) + (c-'0');
x *= flag;
return;
}
template<class Num>void write(Num x)
{
if(x < 0) putchar('-'), x = -x;
static char s[20];int sl = 0;
while(x) s[sl++] = x%10 + '0',x /= 10;
if(!sl) {putchar('0');return;}
while(sl) putchar(s[--sl]);
}
const int maxn = 6005;
struct Edge
{
int v, next;
Edge(int v = 0,int next = 0):v(v),next(next){}
}edge[maxn];
int head[maxn], el, rdu[maxn];
int n, w[maxn], dp[maxn][2];
void clear()
{
el = 0, memset(head, 0, sizeof(head));
memset(dp, 0, sizeof(dp));
memset(rdu, 0, sizeof(rdu));
}
void newedge(int u,int v)
{
++rdu[v], edge[++el] = Edge(v, head[u]), head[u] = el;
}
void init()
{
int u, v;
for(int i = 1; i <= n; i++) read(w[i]);
while(true)
{
read(v), read(u);
if(!(u + v)) break;
newedge(u, v);
}
for(int i = 1;i <= n; i++)
if(!rdu[i]) newedge(0, i);
}
void solve(int x)
{
for(int i = head[x], p; i; i = edge[i].next)
{
solve(p = edge[i].v);
dp[x][0] += dp[p][1], dp[x][1] += dp[p][0];
}
dp[x][1] = std::max(dp[x][1] + w[x], dp[x][0]);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1520.in","r",stdin);
freopen("1520.out","w",stdout);
#endif
while(scanf("%d", &n) != EOF)
{
clear(), init(), solve(0);
write(dp[0][0]), puts("");
}
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}