Optimal way of filling 2 knapsacks?

后端 未结 3 431
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 2020-12-08 12:00

    The original DP assumes you mark in the dp array that values which you can obtain in the knapsack, and updates are done by consequently considering the elements.
    In case of 2 knapsacks you can use 2-dimensional dynamic array, so dp[ i ][ j ] = 1 when you can put weight i to first and weight j to second knapsack. Update is similar to original DP case.

    0 讨论(0)
  • 2020-12-08 12:10

    The recursive formula is anybody is looking:

    Given n items, such that item i has weight wi and value pi. The two knapsacks havk capacities of W1 and W2.

    For every 0<=i<=n, 0<=a<=W1, 0<=b<=W2, denote M[i,a,b] the maximal value.

    for a<0 or b<0 - M[i,a,b] = −∞ for i=0, or a,b=0 - M[i,a,b] = 0

    The formula: M[i,a,b] = max{M[i-1,a,b], M[i-1,a-wi,b] + pi, M[i-1,a,b-wi] + pi}

    Every solution to the problem with i items either has item i in knapsack 1, in knapsack 2, or in none of them.

    0 讨论(0)
提交回复
热议问题