树形dp
#include <iostream> #include <cstring> #include <cstdio> #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <list> #include <map> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <numeric> #include <functional> using namespace std; #define LL long long #define DB double #define N 100005 const int INF = 0x3f3f3f3f; const LL INFF = 1LL << 60; const DB EPS = 1e-9; const DB OO = 1e15; const DB PI = acos(-1.0); int val[N],dp[N][2],f[N]; vector<int>G[N]; void dfs(int rt) { int i,len = G[rt].size(); dp[rt][1] = val[rt]; for(i = 0 ; i < len ; i++) dfs(G[rt][i]); for(i = 0 ; i < len ; i++) { dp[rt][0]+=max(dp[G[rt][i]][0],dp[G[rt][i]][1]); dp[rt][1]+=dp[G[rt][i]][0]; } } int main() { int n,i,j,a,b; while(~scanf("%d",&n)) { memset(G,0,sizeof(G)); for(i = 1 ; i <= n ; i++) { scanf("%d",&val[i]); f[i] = -1; dp[i][0] = dp[i][1] = 0; } while(scanf("%d %d",&a,&b),a+b) { f[a] = b; G[b].push_back(a); } a = 1; while(f[a]!=-1) a = f[a]; dfs(a); printf("%d ",max(dp[a][0],dp[a][1])); } return 0; }