400
Always wanted to contact the multi-knapsack problem, and today finally met.
This is a multi-knapsack problem, simply put, is that each weight of the item is not only one, is not an infinite, but a limited number of
The first idea is to convert to a common knapsack problem to solve, that is, each category of items as a single item
The code is as follows
1#include <cstdio>2#include <iostream>3#include <cstring>4 using namespacestd;5 intn,m;6 intp[102];7 intw[102];8 intc[102];9 intdp[102];Ten One intMainintargcChar Const*argv[]) A { - intC; - //freopen ("Input.txt", "R", stdin); the while(SCANF ("%d", &c)! =EOF) { - while(c--) { -scanf"%d%d",&n,&m); - for(inti =0; I < m; i++) { +scanf" %d%d%d",&p[i],&w[i],&c[i]); - } +Memset (DP,0,sizeof(DP)); A for(inti =0; I < m; i++) { at for(intj =1; J <= C[i]; J + +) { - for(intk = n; K >= P[i]; k--) { -Dp[k] = max (dp[k],dp[k-p[i]]+w[i]); - } - } - in } -printf"%d\n", Dp[n]); to } + } - return 0; the}
Of course, there are some ingenious solutions to this problem.
For example, if an item has 6 pieces, if we divide it into 1 + 2 + 3 pieces, you will find that you can make up any 1 to 6 number
Such a splitting method is to divide a number into 2 of the power of the sum, if not the whole, then the last number is poor
For example, 10 can be split into 1 +2 + 4 + 3
So we can use these numbers to make things that are worth something.
The code is as follows:
1#include <cstdio>2#include <iostream>3#include <cstring>4 using namespacestd;5 intn,m;6 intp[2002];7 intw[2002];8 intc[2002];9 intdp[2002];Ten One intMainintargcChar Const*argv[]) A { - intC; - //freopen ("Input.txt", "R", stdin); the while(SCANF ("%d", &c)! =EOF) { - while(c--) { -scanf"%d%d",&n,&m); - intCNT =0; + for(inti =0; I < m; i++) { - intpt,wt,ct; +scanf" %d%d%d",&pt,&wt,&CT); A intc =1; at while(Ct-c >0) { -P[CNT] = c *pt; -W[CNT] = c *wt; -CT = ct-C; -cnt++; -C *=2; in } -P[CNT] = ct*pt; toW[CNT] = ct*wt; +cnt++; - } theMemset (DP,0,sizeof(DP)); * for(inti =0; I < CNT; i++) { $ for(intk = n; K >= P[i]; k--) {Panax NotoginsengDp[k] = max (dp[k],dp[k-p[i]]+w[i]); - } the + } Aprintf"%d\n", Dp[n]); the } + } - return 0; $}