Same as poj 3342
Http://www.cnblogs.com/wuyiqi/archive/2012/03/08/2385680.html
View code
# Include <cstdio>
# Include <cstring>
# Include <iostream>
# Include <algorithm>
# Include <vector>
# Include < String >
# Include <map>
Using Namespace STD;
# Define Max (A, B) A> B? A: B
Const Int Maxn = 6010 ;
Vector < Int > Edge [maxn];
Int DP [ 6010 ] [ 2 ];
Int W [ 6010 ];
Int N;
Void DFS ( Int U, Int P)
{
Int I, J;
DP [u] [ 1 ] = W [u];
DP [u] [ 0 ] = 0 ;
For (I = 0 ; I <edge [u]. Size (); I ++)
{
Int V = edge [u] [I];
If (V = P) Continue ;
DFS (v, U );
DP [u] [ 1 ] + = DP [v] [ 0 ];
DP [u] [ 0 ] + = Max (DP [v] [ 0 ], DP [v] [ 1 ]);
}
}
Int In [Maxn];
Int Main ()
{
Int I, J, K, S, E;
For (I = 0 ; I <= 6000 ; I ++) edge [I]. Clear ();
Scanf ( " % D " , & N );
For (I = 1 ; I <= N; I ++) scanf ( " % D " , & W [I]);
Memset ( In , 0 ,Sizeof ( In ));
While (Scanf ( " % D " , & E, & S), (E + S )! = 0 )
{
In [E] ++;
Edge [s]. push_back (E );
} Int Flag =- 1 ;
For (I =1 ; I <= N; I ++)
If ( In [I] = 0 )
{
Flag = I;
Break ;
}
DFS (flag, flag );
Printf ( " % D \ n " , Max (DP [flag] [ 0 ], DP [flag] [ 1 ]);
Return 0 ;
}