是否可以为需要每个项目数量的1/0背包问题编写动态解决方案?
例如背包需要:
item_one中的1个
2项目_two
item_three中的3个
item_four中的1个
1项目_five
item_six中的1个
每个项目都有一个重量,最大重量为60000,所以在这个意义上它只是一个普通的背包问题。
除此之外唯一的区别是我试图最小化价值而不是最大化。
这是我在vba中的强力代码,但我在物品上运行这个,所以我需要一个更快的解决方案。谢谢你的帮助!
Function knapsacksolver(item_one, item_two, item_three, item_four, item_five, item_six)
Dim knapsack As Variant
ReDim knapsack(1 To 9, 1 To 5) As Variant
Dim Value As Long
Dim MinValue As Long
Dim Cap As Long
Dim weight As Long
MinValue = 9999999
weight = 0
Cap = 60000
For i = 1 To UBound(item_one)
For j = 1 To UBound(item_two)
For t = 1 To UBound(item_two)
If j <> t Then
For m = 1 To UBound(item_three)
For n = 1 To UBound(item_three)
If n <> m Then
For p = 1 To UBound(item_three)
If n <> p Then
For q = 1 To UBound(item_four)
For r = 1 To UBound(item_five)
For s = 1 To UBound(item_six)
weight = item_one(i, 3) + item_two(j, 3) + item_two(t, 3) + item_three(m, 3) + item_three(n, 3) + item_three(p, 3) + item_four(q, 3) + item_five(r, 3) + item_six(s, 3)
Value = item_one(i, 4) + item_two(j, 4) + item_two(t, 4) + item_three(m, 4) + item_three(n, 4) + item_three(p, 4) + item_four(q, 4) + item_five(r, 4) + item_six(s, 4)
If Value < MinValue And weight < Cap Then
MinValue = Value
'adding attribute from each item to array'
knapsack(1, 1) = item_one(i, 1)
knapsack(1, 2) = item_one(i, 2)
knapsack(1, 3) = item_one(i, 3)
knapsack(1, 4) = item_one(i, 4)
knapsack(1, 5) = item_one(i, 5)
knapsack(2, 1) = item_two(j, 1)
knapsack(2, 2) = item_two(j, 2)
knapsack(2, 3) = item_two(j, 3)
knapsack(2, 4) = item_two(j, 4)
knapsack(2, 5) = item_two(j, 5)
knapsack(3, 1) = item_two(t, 1)
knapsack(3, 2) = item_two(t, 2)
knapsack(3, 3) = item_two(t, 3)
knapsack(3, 4) = item_two(t, 4)
knapsack(3, 5) = item_two(t, 5)
knapsack(4, 1) = item_three(m, 1)
knapsack(4, 2) = item_three(m, 2)
knapsack(4, 3) = item_three(m, 3)
knapsack(4, 4) = item_three(m, 4)
knapsack(4, 5) = item_three(m, 5)
knapsack(5, 1) = item_three(n, 1)
knapsack(5, 2) = item_three(n, 2)
knapsack(5, 3) = item_three(n, 3)
knapsack(5, 4) = item_three(n, 4)
knapsack(5, 5) = item_three(n, 5)
knapsack(6, 1) = item_three(p, 1)
knapsack(6, 2) = item_three(p, 2)
knapsack(6, 3) = item_three(p, 3)
knapsack(6, 4) = item_three(p, 4)
knapsack(6, 5) = item_three(p, 5)
knapsack(7, 1) = item_four(q, 1)
knapsack(7, 2) = item_four(q, 2)
knapsack(7, 3) = item_four(q, 3)
knapsack(7, 4) = item_four(q, 4)
knapsack(7, 5) = item_four(q, 5)
knapsack(8, 1) = item_five(r, 1)
knapsack(8, 2) = item_five(r, 2)
knapsack(8, 3) = item_five(r, 3)
knapsack(8, 4) = item_five(r, 4)
knapsack(8, 5) = item_five(r, 5)
knapsack(9, 1) = item_six(s, 1)
knapsack(9, 2) = item_six(s, 2)
knapsack(9, 3) = item_six(s, 3)
knapsack(9, 4) = item_six(s, 4)
knapsack(9, 5) = item_six(s, 5)
End If
weight = 0
Next s
Next r
Next q
End If
Next p
End If
Next n
Next m
End If
Next t
Next j
Next i
knapsacksolver = knapsack
End Function