The following is based on the blog of the "distant market:
Concept:Tree-like DP is the DP on a tree. The basic idea is to exit the parent node information from the child node information.
Data Structure: The tree is generally multi-cross, so the left son and right brother notation is used.
Eg:HDU 1520 Analysis
Step-by-step analysis:
Simplest
If a. Data> B. Data + C. Data, A should be selected.
Further:
CodeThey worship:
# Include <stdio. h> # include <string. h> # define n 6005 struct node {int from, to, next;} edge [2 * n]; int head [N], Tol, visit [N], val [N], degree [N], DP [N] [3]; void add (int A, int B) {edge [tol]. from = A; edge [tol]. to = B; edge [tol]. next = head [a]; head [a] = tol ++;} int max (int A, int B) {return A> B? A: B;} void DFS (INT root) {Int J, U, ans1, ans0; visit [root] = 0; ans1 = ans0 = 0; for (j = head [root]; J! =-1; j = edge [J]. Next) {u = edge [J]. To; If (! Visit [u]) DFS (U); ans0 + = max (DP [u] [0], DP [u] [1]); ans1 + = DP [u] [0];} DP [root] [1] = ans1 + val [root]; // indicates the maximum value that can be selected for the subtree with the node as the root DP [root] [0] = ans0; // indicates that the node is not selected, maximum value that can be selected for the subtree with this node as the root} int main () {int I, n, sum, a, B; while (scanf ("% d ", & N )! = EOF) {for (I = 1; I <= N; I ++) scanf ("% d", & Val [I]); memset (Head,-1, sizeof (head); memset (degree, 0, sizeof (degree); Tol = 0; while (scanf ("% d", & A, & B )! = EOF) {if (a = 0 & B = 0) break; add (B, A); degree [a] ++;} memset (visit, 0, sizeof (visit); memset (DP, 0, sizeof (DP); sum = 0; for (I = 1; I <= N; I ++) {If (degree [I] = 0) {DFS (I); sum + = max (DP [I] [0], DP [I] [1]) ;}} printf ("% d \ n", sum);} return 0 ;}
, As shown in the first step,
If you select a, you cannot select B and C. You can also select D and E when C is not selected.
Therefore, for a node, record two values at the same time, the first selected value, node. Choose; the second record does not select a value, node. unchoose;
In this way, we need to compare:
1. A. Choose = A. Data + B. unchoose + C. unchoose;
2. A. unchoose = chmax (B. Choose, B. unchoose) + chmax (B. Choose, B. unchoose );
The resulting formula is the DP formula.
Initialization: for initial values, the data fields of leaf node B, D, and E are their own values, the choose field is the data value, and the unchoose field is 0.
The branch node has two data domains which are their own values. The choose and unchoose fields need to be obtained by calling recursive functions;
The branch node has a data field that is its own value. The choose field calls the choose and unchoose of the corresponding child;