Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=2191
Standard Multi-pack
Topic
There are n kinds of goods and a backpack with a capacity of V. (i) Items with a maximum of n[i] pieces available, each cost is c[i], the value is w[i]. The solution of which items are loaded into the backpack allows the sum of the costs of these items to be no more than the backpack capacity and the maximum value.
Basic algorithms
This topic is very similar to the complete knapsack problem. The basic equation simply changes the equation of the complete knapsack problem slightly, because there are n[i]+1 strategies for item I: Take 0 pieces, take 1 pieces ... Take n[i] pieces. F[I][V] indicates that the first I item fits into the maximum weight of a backpack with a capacity of V, then there is a state transition equation:
F[i][v]=max{f[i-1][v-k*c[i]]+k*w[i]|0<=k<=n[i]}
Complexity is O (V*σn[i]).
Conversion to 01 knapsack problem
Another good way to write the basic method is to convert to 01 knapsack solution: The item I to n[i] pieces 01 Backpack items, then get the number of items Σn[i] 01 knapsack problem, the direct solution, the complexity is still O (V*σn[i]).
But we expect to turn it into a 01 knapsack problem that can reduce complexity like a full backpack. Still taking into account the idea of binary, we consider replacing item I with a number of items, so that each strategy that is desirable for article I in the original question is 0. N[i] pieces--can be equivalent to taking a number of items after substitution. In addition, the strategy of taking more than n[i] pieces will not appear.
The method is to divide the item I into several items, each of which has a factor, and the cost and value of the item are multiplied by this factor. The coefficients are 1,2,4,..., 2^ (k-1), n[i]-2^k+1, and K is the largest integer that satisfies n[i]-2^k+1>0. For example, if N[i] is 13, the items are divided into four items with coefficients of 1,2,4,6 respectively.
#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>#include<map>using namespacestd;#defineMet (A, b) memset (A, B, sizeof (a))#defineINF 0x3f3f3f3f#defineN 2310intC[n], w[n], K;voidSlove (intCostintWeightintCnt///Binary thinking, dividing cnt into 1,2,4,8,16 ... deposit in C and W,//press 01 backpack to process{ intm =1; while(CNT >=m) {C[k]= m*Cost ; W[k+ +] = m*weight; CNT-=m; M= m*2; } if(cnt>0) {C[k]= cnt*Cost ; W[k+ +] = cnt*weight; }}intMain () {intT, V, N; intCost , weight, CNT, dp[n]; scanf ("%d", &T); while(t--) {Met (DP,0); Met (C,0); Met (W,0); K=1; scanf ("%d%d", &v, &N); for(intI=1; i<=n; i++) {scanf (" %d%d%d", &cost, &weight, &CNT); Slove (cost, weight, CNT); } for(intI=1; i<k; i++) { for(intJ=v; j>=c[i]; j--) {Dp[j]= Max (Dp[j], dp[j-c[i]]+W[i]); }} printf ("%d\n", Dp[v]); } return 0;}
View Code
Mourn the death of 512 Wenchuan earthquake--cherish now, Thanksgiving life--hdu2191 (Multiple backpack template)