Nik*_*nka 17 algorithm knapsack-problem dynamic-programming graph-algorithm
在一个背包的情况下,用于最佳地填充背包的动态编程算法很好地工作.但是,是否有一种有效的已知算法可以最佳地填充2个背包(容量可能不相等)?
我尝试了以下两种方法,但它们都不正确.
问题陈述(另见维基百科的背包问题):
我们必须用一组物品(每个物品具有重量和值)填充背包,以便最大化我们可以从物品获得的值,同时总重量小于或等于背包尺寸.
我们不能多次使用一个项目.
IVl*_*lad 11
我将假设每个n
项目只能使用一次,您必须最大化您的利润.
原装背包是 dp[i] = best profit you can obtain for weight i
for i = 1 to n do
for w = maxW down to a[i].weight do
if dp[w] < dp[w - a[i].weight] + a[i].gain
dp[w] = dp[w - a[i].weight] + a[i].gain
Run Code Online (Sandbox Code Playgroud)
现在,因为我们有两个背包,我们可以使用 dp[i, j] = best profit you can obtain for weight i in knapsack 1 and j in knapsack 2
for i = 1 to n do
for w1 = maxW1 down to a[i].weight do
for w2 = maxW2 down to a[i].weight do
dp[w1, w2] = max
{
dp[w1, w2], <- we already have the best choice for this pair
dp[w1 - a[i].weight, w2] + a[i].gain <- put in knapsack 1
dp[w1, w2 - a[i].weight] + a[i].gain <- put in knapsack 2
}
Run Code Online (Sandbox Code Playgroud)
时间复杂度是O(n * maxW1 * maxW2)
,maxW
背包可以承载的最大重量.请注意,如果容量很大,则效率不高.