Two knapsack, dynamic programming

雨燕双飞 提交于 2019-12-23 20:28:55

问题


Edit: Codes are fixed.

I'm trying to solve the problem below with dynamic programming but it gives 15 instead of 18. I'm looking for an error for about an hour but I couldn't figure it out.

Problem: There is two knapsack with capacities c1, c2 and an n-element set. Each element has a w1 (its weight when put in the first knapsack), a w2 (its weight when put in the second knapsack) and a value. I need to find two disjoint subsets of the n-element set that fits in the corresponding knapsacks and has the maximum total value.

w1: Item's weight when put in knapsack 1

w2: Item's weight when put in knapsack 2

v : value

Answer:

Knapsack 1: Item 1 Item 2

Knapsack 2: Item 3 Item 4

Algorithm: (python)

w1 = [2, 3, 2, 5]
w2 = [2, 5, 1, 5]
v = [4, 3, 5, 6]

c1 = 5
c2 = 6
n = 4

arr = [[[0 for x in range(c2 + 1)] for y in range(c1 + 1)] for z in range(n + 1)]

for i in range(1, n + 1):
    for j in range(0, c1 + 1):
        for k in range(0, c2 + 1):
            weight1 = w1[i - 1]
            weight2 = w2[i - 1]
            val = v[i - 1]

            if weight1 <= j and weight2 <= k: #item fits both knapsack
                arr[i][j][k] = max(val + arr[i - 1][j - weight1][k], #put knapsack 1
                                   val + arr[i - 1][j][k - weight2], #put knapsack 2
                                   arr[i - 1][j][k])
            elif weight1 <= j: #just knapsack 1
                arr[i][j][k] = max(val + arr[i - 1][j - weight1][k], #take
                                   arr[i - 1][j][k])
            elif weight2 <= k: #just knapsack 2
                arr[i][j][k] = max(val + arr[i - 1][j][k - weight2], #take
                                   arr[i - 1][j][k])
            else:
                arr[i][j][k] = arr[i - 1][j][k]

print arr[n][c1][c2]

I tried this algorithm, it worked. Here is the code: Knapsack algorithm for two bags

w1 = [2, 3, 2, 5]
w2 = [2, 5, 1, 5]
v = [4, 3, 5, 6]

c1 = 5
c2 = 6
n = 4

result = -1

arr = [[0 for y in range(c2 + 1)] for z in range(c1 + 1)]

for i in range(1, n + 1):
    weight1 = w1[i - 1]
    weight2 = w2[i - 1]
    val = v[i - 1]

    for j in range(c1, -1, -1):
        for k in range(c2, -1, -1):
            if weight1 <= j and weight2 <= k: #item fits both knapsack
                arr[j][k] = max(val + arr[j - weight1][k],
                                val + arr[j][k - weight2],
                                arr[j][k])
            elif weight1 <= j: #just knapsack 1
                arr[j][k] = max(val + arr[j - weight1][k],
                                arr[j][k])
            elif weight2 <= k: #just knapsack 2
                arr[j][k] = max(val + arr[j][k - weight2],
                                arr[j][k])


print arr[c1][c2]

来源:https://stackoverflow.com/questions/46635518/two-knapsack-dynamic-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!