樹形DP模板。spa
#include <cstdio> #include <algorithm> using namespace std; int n, r[6003], f[6003][2], v[6003], root, ans; int head[6003], nex[6003], to[6003]; inline void add(int x, int y) { nex[++head[0]]=head[x], head[x]=head[0], to[head[0]]=y; } void dp(int x) { f[x][1]=r[x]; for (register int k=head[x]; k; k=nex[k]) dp(to[k]), f[x][0]+=max(f[to[k]][0], f[to[k]][1]), f[x][1]+=f[to[k]][0]; } int main() { scanf("%d", &n); for (register int i=1; i<=n; ++i) scanf("%d", &r[i]); for (register int i=1, l, k; i<n; ++i) scanf("%d%d", &l, &k), add(k, l), v[l]=1; for (register int i=1; i<=n; ++i) if (!v[i]) {root=i; break; } dp(root); printf("%d\n", max(f[root][0], f[root][1])); return 0; }