思路:
挺简单的树形dp
#include<cstdio> #include<iostream> #include<cstdlib> #include<vector> using namespace std; const int maxn = 200010; void qread(int &x) { x = 0; register int ch = getchar(), flag = 0; while(ch < '0' || ch > '9') {if(ch == '-') flag = 1; ch = getchar();} while(ch >= '0' && ch <= '9') x = 10 * x + ch - 48, ch = getchar(); if(flag) x = -x; } int n, rt = 0, cnt; int val[maxn]; int deep[maxn]; int f[maxn]; int head[maxn]; int go[maxn << 1]; int nxt[maxn << 1]; int dp[maxn][2]; inline void init(){ qread(n); for(int i=1; i<=n; ++i) qread(val[i]); int x, y; qread(x), qread(y); while(x || y){ go[++cnt] = x; nxt[cnt] = head[y]; head[y] = cnt; f[x] = y; qread(x), qread(y); } for(int i=1; i<=n; ++i) if(!f[i]) rt = i; } void DP(int x){ dp[x][1] = val[x]; for(int i = head[x]; i; i = nxt[i]){ DP(go[i]); dp[x][1] += dp[go[i]][0]; dp[x][0] += max(dp[go[i]][0], dp[go[i]][1]); } } int main(void){ init(); DP(rt); printf("%d\n", max(dp[rt][0], dp[rt][1])); }
---恢复内容结束---