1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <bits/stdc++.h> using namespace std; const int N = 6001; int u, v, r[N], h[N], e[N], ne[N], idx, d[N]; int n, root, f[N][2]; void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } void dfs(int u) { f[u][0] = 0; f[u][1] = r[u]; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; dfs(v); f[u][0] += max(f[v][0], f[v][1]); f[u][1] += f[v][0]; } } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d", &r[i]); for (int i = 1; i < n; ++i) { scanf("%d%d", &v, &u); add(u, v); ++d[v]; } for (int i = 1; i <= n; ++i) if (!d[i]) { root = i; break; } dfs(root); printf("%d\n", max(f[root][0], f[root][1])); return 0; }
|