树状dp搞之。。。
再次吐槽,各种不会dp,惨淡的人生啊!!!
/*
* Author: stormdpzh
* Created Time: 2012/7/29 20:45:46
* File Name: poj_2342.cpp
*/
#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#define sz(v) ((int)(v).size())
#define rep(i, n) for(int i = 0; i < n; i++)
#define repf(i, a, b) for(int i = a; i <= b; i++)
#define repd(i, a, b) for(int i = a; i >= b; i--)
#define out(n) printf("%d\n", n)
#define mset(a, b) memset(a, b, sizeof(a))
#define wh(n) while(1 == scanf("%d", &n))
#define whz(n) while(1 == scanf("%d", &n) && n != 0)
#define lint long long
using namespace std;
const int MaxN = 6005;
vector<int> edge[MaxN];
int n;
bool son[MaxN];
int val[MaxN];
int f[MaxN][2];
void gao(int u)
{
f[u][0] = 0;
f[u][1] = val[u];
rep(i, sz(edge[u])) {
int v = edge[u][i];
gao(v);
f[u][1] += f[v][0];
f[u][0] += max(f[v][0], f[v][1]);
}
}
int main()
{
wh(n) {
for(int i = 1; i <= n; i++) scanf("%d", &val[i]);
for(int i = 1; i <= n; i++) edge[i].clear();
int a, b;
while(2 == scanf("%d%d", &a, &b) && (a || b)) {
edge[b].push_back(a);
son[a] = true;
}
int root;
for(int i = 1; i <= n; i++) if(!son[i]) {
root = i;
break;
}
gao(root);
out(max(f[root][0], f[root][1]));
}
return 0;
}