We regard patience as the size of the backpack, experience as the value, and increase the number of one-dimensional constraints. This is a typical knapsack problem.
We define DP [J] [k] to indicate that the backpack capacity is J, and select the maximum value that K items can achieve. In fact, this is the result of the previous dimension omitted. We can clearly define DP [I] [J] [k] to indicate the items in the previous I, for a backpack with a size of J, select the maximum value that K items can reach. After we list the state transition equation, we find that we can omit the previous one to ensure the correctness of the answer, therefore, we use the first definition to optimize the space.
Status transfer is relatively simple.CodeYou will know.
# Include <iostream> # include <cstdio> # include <cstdlib> # include <cstring> using namespace STD; const int max = 110; int DP [Max] [Max]; int main () {int n, m, K, s; int V [Max], W [Max]; while (scanf ("% d ", & N, & M, & K, & S )! = EOF) {for (INT I = 1; I <= K; I ++) {scanf ("% d", & W [I], & V [I]);} memset (DP, 0, sizeof (DP); int ans =-1; bool flag = false; For (Int J = 1; j <= m; j ++) {for (INT I = 1; I <= K; I ++) {for (int K = 1; k <= s; k ++) {for (INT x = 0; x <= K & x * V [I] <= J; X ++) {DP [J] [k] = max (DP [J] [K], DP [J-x * V [I] [k-x] + x * W [I]); If (DP [J] [k]> = N) {flag = true; ans = J; break;} If (FLAG) printf ("% d \ n", M-ans); else printf ("-1 \ n");} return 0 ;}