Test instructions: A little doll got a scholarship to go shopping, there are n things divided into K group, each thing has a cost and value, ask in each group of things to buy at least one of the conditions, the little doll with his scholarship to buy things can get the maximum value.
Idea: Define state Dp[i][v] indicates that at least one of the items in [1, I] group is purchased with V (Backpack capacity) so much money can get how much value.
State transition equation:
if (Dp[i][v-cost[i][j]]! =-1)
DP[I][V] = max (Dp[i][v], Dp[i][v-cost[i][j]] + val[i][j]);
if (Dp[i-1][v-cost[i][j]]! =-1)
DP[I][V] = max (Dp[i][v], Dp[i-1][v-cost[i][j]] + val[i][j]);
The items representing group I are not and are the first purchase.
The order of these two state transfer equations cannot be changed because there is a cost of 0 items ...
1#include <iostream>2#include <cstring>3#include <cstdio>4 using namespacestd;5 6 Const intN =101;7 Const intM =10001;8 Const intK = One;9 intDp[k][m];Ten intCost[k][n]; One intVal[k][n]; A intNum[k]; - - intMain () the { - intN, M, K; - while(SCANF ("%d%d%d", &n, &m, &k)! =EOF) - { +memset (NUM,0,sizeof(num)); - for(inti =1; I <= N; i++ ) + { A intG; atscanf"%d", &g); -scanf"%d%d", &cost[g][num[g]], &Val[g][num[g]]); -num[g]++; - } -Memset (DP,-1,sizeof(DP)); -memset (dp[0],0,sizeof(dp[0]) ); in for(inti =1; I <= K; i++ ) - { to for(intj =0; J < Num[i]; J + + ) + { - for(intv = m; V >= Cost[i][j]; v-- ) the { * if(Dp[i][v-cost[i][j]]! =-1 ) $ {Panax NotoginsengDP[I][V] = max (Dp[i][v], Dp[i][v-cost[i][j]] +val[i][j]); - } the if(Dp[i-1][V-COST[I][J]]! =-1 ) + { ADP[I][V] = max (Dp[i][v], dp[i-1][V-COST[I][J]] +val[i][j]); the } + } - } $ } $ if(Dp[k][m]! =-1 ) - { -printf"%d\n", Dp[k][m]); the } - ElseWuyi { theprintf"impossible\n"); - } Wu } - return 0; About}
HDU 3033 Pack Backpack (select at least one per group)