題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1520
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int N = 6666;
int v[N], fa[N], dp[N][2];
vector<int> vec[N];
void dfs(int rt)
{
int len = vec[rt].size();
dp[rt][1] = v[rt];
for(int i=0; i<len; i++) dfs(vec[rt][i]);
for(int i=0; i<len; i++) {
dp[rt][0] += max(dp[vec[rt][i]][0], dp[vec[rt][i]][1]);
dp[rt][1] += dp[vec[rt][i]][0];
}
}
int main()
{
int n, a, b;
while(~scanf("%d", &n)) {
for(int i=1; i<=n; i++) {
scanf("%d", &v[i]);
vec[i].clear();
fa[i] = -1; // 初始化樹根標記
dp[i][0] = dp[i][1] = 0;
}
while(scanf("%d%d", &a, &b), a||b) {
fa[a] = b;
vec[b].push_back(a); // 建立結點間的父子關係
}
int rt = 1;
while(fa[rt] != -1) rt = fa[rt]; // 尋找樹根
dfs(rt);
printf("%d\n", max(dp[rt][0], dp[rt][1]));
}
return 0;
}