Because the relationship between superiors forms a tree, we can consider the problem from the perspective of tree DP. F [cur] [0] indicates the maximum value of the subtree value when the current node is not selected, and f [cur] [1] indicates the maximum value of the subtree value when the current node is selected, if the current node is not selected, its subnodes are optional or not selected, therefore, F [cur] [0] must add the max {f [x] [1], F [x] [0]} of all subnodes X. If you select the current node, its subnodes must not be selected. Therefore, F [cur] [1] must add f [x] [0] Of all subnodes X and the value of the current node.
# Include <stdio. h> # Include < String . H> # Define Maxd 6010 Int N, first [maxd], next [maxd], V [maxd], E, DGR [maxd]; Int A [maxd], F [maxd] [ 2 ]; Int Max ( Int X, Int Y ){ Return X> Y? X: Y ;} Void Add ( Int X, Int Y) {v [E] = Y; next [E] = First [X], first [x] = e ++ ;} Void Init (){ Int I, L, K; memset (DGR, 0 , Sizeof (DGR); memset (first, - 1 , Sizeof (First); e = 0 ; For (I = 1 ; I <= N; I ++ ) Scanf ( " % D " ,& A [I]); For (;) {Scanf ( " % D " , & L ,& K ); If (! L &&! K) Break ; Add (K, L ), ++ DGR [l] ;}} Void DP ( Int Cur ){ Int I, Max, sum; max = Sum = 0 ; For (I = first [cur]; I! =- 1 ; I = Next [I]) {dp (V [I]); max + = Max (F [V [I] [ 0 ], F [V [I] [ 1 ]); Sum + = F [V [I] [ 0 ];} F [cur] [ 1 ] = Sum + A [cur]; F [cur] [ 0 ] = Max ;} Void Solve (){ Int I, J, K, ANS = 0 ; For (I = 1 ; I <= N; I ++ ) If (DGR [I] = 0 ) {Dp (I); ans + = Max (F [I] [ 0 ], F [I] [ 1 ]);} Printf ( " % D \ n " , ANS );} Int Main (){ While (Scanf ( " % D " , & N) = 1 ) {Init (); solve ();} Return 0 ;}