Tree dp
dp[N][2]:
// dp for the current node is selected or not selected
// dp [i] [0] ; // not selected
// dp [i] [1] ; // selected from
State transition equation (the key):
for(int i=0;i<v[root].size();i++) { DP [the root] [ 0 ] + DP = [V [the root] [I]] [ . 1 ]; // if the current node is not selected, the sub-node must choose DP [the root] [ . 1 ] + = min (DP [V [the root] [I]] [ . 1 ], DP [V [the root] [I]] [ 0 ]); // current node is selected, a child node (selected / not selected) }
1 // given a node number n ~ n-1 0 2 // each station a sentinel node, each sentry observed with their two adjacent sides 3 // Q required minimum number of sentinel can be observed All edges . 4 . 5 #include < String .h> . 6 #include <the iostream> . 7 #include <stdio.h> . 8 #include <algorithm> . 9 #include <Queue> 10 #include <Vector> . 11 #include <Map> 12 is #include <the cmath> 13 is the using namespace STD; 14 #define INF 0x3f3f3f3f 15 #define inff 0x3f3f3f3f3f3f3f3f 16 const int N = 1550 ; . 17 #define MOD 998 244 353 18 is typedef Long Long LL; . 19 20 is int n-; 21 is Vector < int > V [N]; 22 is int F [N], DP [N] [ 2 ]; 23 is // DP for the current node is selected or not selected 24 // DP [I] [0]; // no option 25 // DP [I] [. 1]; // option 26 is void DFS ( int the root) 27 { 28 DP [the root] [ 0 ] =0 ; // this is not the root node is selected from 29 DP [the root] [ . 1 ] = . 1 ; // currently selected root 30 for ( int I = 0 ; I <V [the root] .size (); I ++ ) 31 is DFS ( V [the root] [I]); 32 for ( int I = 0 ; I <V [the root] .size (); I ++ ) 33 is { 34 is DP [the root] [ 0 ] + = DP [V [the root] [I ]] [ 1 ]; // if the current node is not selected, the sub-node must be selected from the 35 DP [the root] [ 1 ] + = min (DP [V [the root] [I]] [ 1], DP [V [the root] [I]] [ 0 ]); // current node is selected, a child node (selected / not selected) 36 } 37 [ } 38 is 39 int main () 40 { 41 is the while (~ Scanf ( " % D " , & n-)) 42 is { 43 is Memset (F, - . 1 , the sizeof (F)); // since the node ID 0 ~ n--. 1 44 is for ( int I = . 1 ; I <= n-; I ++ ) 45 { 46 is int the root, Node, Son; 47 Scanf (" % D: (% D) " , & the root, & Node); 48 V [the root] .clear (); // remember Clear 49 for ( int J = . 1 ; J <= Node; J ++ ) 50 { 51 is Scanf ( " % D " , & Son); 52 is V [the root] .push_back (Son); // unidirectional edge 53 is F [Son] = the root; 54 is } 55 } 56 is int X = 0 ; 57 is the while (F [X] ! = -. 1 ) 58 X = F [X]; // find the root of the whole tree 59 DFS (X); 60 int Minn = min (DP [X] [ 0 ], DP [X] [ . 1 ]); 61 is the printf ( " % D \ n- " , Minn); 62 is } 63 is return 0 ; 64 }
Bipartite graph matching (Hungarian Algorithm) Exercise