[英]Trying to find the optimal subset for the Greedy knapsack problem(python)
我認為這是找到最佳值的正確算法,但現在我需要找到獲得該值的最佳子集。 幫助將不勝感激!
這些是我的方向:實現一個貪心算法,按價值與重量比的降序排列項目(vi/wi for i = 1, 2, ..., n),然后 select 按此順序排列項目,直到重量下一個項目超過剩余容量(注意:在這個貪婪版本中,我們在第一個包含超過背包容量的項目之后立即停止)。
def greedy_knapsack(val, weight, W, n):
# index = [0, 1, 2, ..., n - 1] for n items
index = list(range(len(val)))
# contains ratios of values to weight
ratio = [v / w for v, w in zip(val, weight)]
QuickSort(ratio, 0, len(ratio) - 1)
max_value = 0
for i in index:
if weight[i] <= W:
max_value += val[i]
W -= weight[i]
else:
max_value += val[i] * W // weight[i]
break
return max_value
在許多情況下,你的貪婪方法會失敗。
一個這樣的微不足道的案例:
weight = [10, 10, 10]
value = [5, 4, 3]
W = 7
在這種情況下,您的算法將選擇 (項目 1) sum = 5,但最佳答案應該是 (項目 2 和 3),總和 = 7。
您需要一種動態編程方法來解決這個問題,並且您可以保留一個矩陣來存儲您以前的狀態,以便您可以重建解決方案並獲取項目列表。
# Prints the items which are put in a
# knapsack of capacity W
def printknapSack(W, wt, val, n):
K = [[0 for w in range(W + 1)]
for i in range(n + 1)]
# Build table K[][] in bottom
# up manner
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i - 1] <= w:
K[i][w] = max(val[i - 1]
+ K[i - 1][w - wt[i - 1]],
K[i - 1][w])
else:
K[i][w] = K[i - 1][w]
# stores the result of Knapsack
res = K[n][W]
print(res)
w = W
for i in range(n, 0, -1):
if res <= 0:
break
# either the result comes from the
# top (K[i-1][w]) or from (val[i-1]
# + K[i-1] [w-wt[i-1]]) as in Knapsack
# table. If it comes from the latter
# one/ it means the item is included.
if res == K[i - 1][w]:
continue
else:
# This item is included.
print(wt[i - 1])
# Since this weight is included
# its value is deducted
res = res - val[i - 1]
w = w - wt[i - 1]
# Driver code
val = [ 60, 100, 120 ]
wt = [ 10, 20, 30 ]
W = 50
n = len(val)
printknapSack(W, wt, val, n)
參考: https://www.geeksforgeeks.org/printing-items-01-knapsack/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.