Backpack VII
Backpack VII (多重背包问题)
bounded knapsack problem (BKP)
Description
Assume that you haven
yuan. There are many kinds of rice in the supermarket. Each kind of rice is bagged and must be purchased in the whole bag. Given theweight
,price
andquantity
of each type of rice, findthe maximum weight
of rice that you can purchase.
Example
Related Problems
Analysis & Solution
多重背包问题
这个问题与 0-1 背包的区别在于,0-1 背包中每种物品有且只有一个,而多重背包中一种物品有nums[i] 个。
Approach - DP
状态:
dp[i][j]
表示从前i
种物品中选取若干种,这若干种物品在总价值不大于j
的前提下,所能获得的最大总重量转移方程:分两种情况。如果第
i
种物品不取,那么dp[x][j] = dp[y][j]
。如果第i
种物品取了,那就可能有amount[i-1]
种取法,那么每一种取法都要考虑,第k
种取法,就会增加k * price[i - 1]
价值(花费)和k * weight[i - 1]
重量。State Transfer Function
dp[i][j] = max(dp[i - 1][j - k * price[i - 1]] + k * weight[i - 1]), k: 0 ~ amounts if j - k * price[i - 1]
初始条件
dp[0][j] = 0
dp[i][0] = 0
答案:
dp[m][n]
2D - DP
1D DP Optimization
这题也可以用 Backpack II 中的一维数组倒序解法。只不过就在倒序遍历价格范围之前,遍历amounts[i - 1]
次第i
中物品有的数量。时间复杂度是O(all * n * sum(amounts[i - 1] )), 空间复杂度是dp[n]
Last updated