Optimal way of filling 2 knapsacks?

后端 未结 3 430
天命终不由人
天命终不由人 2020-12-08 11:28

The dynamic programming algorithm to optimally fill a knapsack works well in the case of one knapsack. But is there an efficient known algorithm that will optimally fill 2 k

3条回答
  •  醉梦人生
    2020-12-08 11:53

    I will assume each of the n items can only be used once, and you must maximize your profit.

    Original knapsack is 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
    

    Now, since we have two knapsacks, we can use 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
                       }
    

    Time complexity is O(n * maxW1 * maxW2), where maxW is the maximum weight the knapsack can carry. Note that this isn't very efficient if the capacities are large.

提交回复
热议问题