状态转移方程:
dp[u][0] = max(dp[v][0],dp[v][1]);
dp[u][1] += dp[v][0];
#include <iostream> #include <cstdio> #include <vector> #include <cstring> #include <algorithm> using namespace std; const int maxn = 6010; vector<int>tree[maxn]; int rat[maxn],deg[maxn],dp[maxn][2]; int max(int x,int y){ return x > y ? x : y; } void dfs(int u){ if(0 == tree[u].size()) { dp[u][1] = rat[u]; return ; } dp[u][1] += rat[u]; for(int i = 0; i < tree[u].size(); i++){ int v = tree[u][i]; dfs(v); dp[u][0] += max(dp[v][0],dp[v][1]); dp[u][1] += dp[v][0]; } } int main() { // freopen("in.txt","r",stdin); int n,l,k,root; while( ~scanf("%d",&n) ){ for( int i = 1; i <= n; i++){ tree[i].clear(); scanf("%d",rat+i); } memset(deg,0,sizeof(deg)); while( ~scanf("%d%d",&l,&k) , l||k){ deg[l]++; tree[k].push_back(l); } memset(dp,0,sizeof(dp)); for( root = 1; root <= n; root ++){ if( !deg[root]){ dfs(root); break; } } printf("%d ",max(dp[root][0],dp[root][1])); } return 0; }