Hdu1561 -- H-ACboy needs your help (tree dp)
H-ACboy needs your helpTime Limit:1000 MSMemory Limit:32768KB64bit IO Format:% I64d & % I64uSubmit Status
Description
ACboy has N courses this term, and he plans to spend at most M days on study. of course, the profit he will gain from different course depending on the days he spend on it. how to arrange the M days for the N courses to maximize the profit?
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers N and M, N is the number of courses, M is the days ACboy has.
Next follow a matrix A [I] [j], (1 <= I <= N <= 100, 1 <= j <= M <= ). A [I] [j] indicates if ACboy spend j days on ith course he will get profit of value A [I] [j].
N = 0 and M = 0 ends the input.
Output
For each data set, your program shocould output a line which contains the number of the max profit ACboy will gain.
Sample Input
2 21 21 32 22 12 12 33 2 13 2 10 0
Sample Output
346
Tree dp No. 1
The dependency given by the question can be composed of several trees, virtualized as a root, node 0, so that all vertices are connected together
In the tree-like dp, the array dp [I] [j] indicates that for the I node, select the j cities to reach the maximum value. After the build is complete, dfs, recursion to the leaf node. dp [Leaf] [1] = the weight of the Leaf. The other values are 0. Then, go back to the parent node, dp [I] [j] = max (dp [I] [j], dp [I] [j-k] + dp [v] [k]) v indicates the child node, and k indicates selecting k cities in the subtree where v is the root node. Then, only j-k cities can be selected in the cities where I is the root node, in this way, each subnode of I is considered as a group in the group backpack to perform operations on the group backpack, to obtain the maximum weight of dp [I] [j] (1 <= j <= m), and then trace back layer by layer.
Note 1: increase the total root, so the required city m should be added with 1.
NOTE 2: because of the dependency, dp [I] [1] must be the weight of the I node, and then the weight that the child node can change, therefore, dp [I] [j], j should be greater than or equal to 2, and k must be smaller than j, leaving a position on the I Node
#include
#include
#include using namespace std;struct node{ int v ; int next ;} edge[1000000] ;int head[300] , p[300] , cnt ;int dp[300][300] ;int n , m ;void add(int u,int v){ edge[cnt].v = v ; edge[cnt].next = head[u] ; head[u] = cnt++ ;}void dfs(int u){ int i , v , j , k ; dp[u][1] = p[u] ; for(i = head[u] ; i != -1 ; i = edge[i].next) { v = edge[i].v ; dfs(v); for(j = m ; j >= 2 ; j--) { for(k = 0 ; k < j ; k++) dp[u][j] = max( dp[u][j], dp[u][j-k]+dp[v][k] ); } }}int main(){ int u , v , i ; while( scanf("%d %d", &n, &m)!=EOF ) { if(n == 0 && m == 0) break; memset(head,-1,sizeof(head)); memset(dp,0,sizeof(dp)); p[0] = cnt = 0 ; for(i = 1 ; i <= n ; i++) { scanf("%d %d", &u, &v); p[i] = v ; add(u,i); } m++ ; dfs(0); printf("%d\n", dp[0][m]); } return 0;}