[英]Printing Items that are in sack in knapsack
Suppose you are a thief and you invaded a house.假设你是一个小偷,你闯入了一所房子。 Inside you found the following items:
在里面你找到了以下物品:
A vase that weights 3 pounds and is worth 50 dollars.一个重 3 磅,价值 50 美元的花瓶。
A silver nugget that weights 6 pounds and is worth 30 dollars.一块重 6 磅、价值 30 美元的银块。
A painting that weights 4 pounds and is worth 40 dollars.一幅重 4 磅、价值 40 美元的画作。
A mirror that weights 5 pounds and is worth 10 dollars.一面镜子重 5 磅,价值 10 美元。
Solution to this Knapsack problem of size 10 pounds is 90 dollars .这个 10 磅大小的背包问题的解决方案是 90 美元。
Table made from dynamic programming is :-由动态规划制成的表是:-
Now i want to know which elements i put in my sack using this table then how to back track ??现在我想知道我用这张表把哪些元素放在了我的袋子里,然后如何回溯??
From your DP table we know f[i][w] = the maximum total value of a subset of items 1..i that has total weight less than or equal to w.从您的 DP 表中我们知道 f[i][w] = 总重量小于或等于 w 的项目 1..i 的子集的最大总值。
We can use the table itself to restore the optimal packing:我们可以使用表格本身来恢复最佳包装:
def reconstruct(i, w): # reconstruct subset of items 1..i with weight <= w
# and value f[i][w]
if i == 0:
# base case
return {}
if f[i][w] > f[i-1][w]:
# we have to take item i
return {i} UNION reconstruct(i-1, w - weight_of_item(i))
else:
# we don't need item i
return reconstruct(i-1, w)
Using a loop :使用循环:
for (int n = N, w = W; n > 0; n--)
{
if (sol[n][w] != 0)
{
selected[n] = 1;
w = w - wt[n];
}
else
selected[n] = 0;
}
System.out.print("\nItems with weight ");
for (int i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(val[i] +" ");
I have an iterative algorithm inspired by @NiklasB.我有一个受@NiklasB 启发的迭代算法。 that works when a recursive algorithm would hit some kind of recursion limit.
当递归算法达到某种递归限制时,它会起作用。
def reconstruct(i, w, kp_soln, weight_of_item):
"""
Reconstruct subset of items i with weights w. The two inputs
i and w are taken at the point of optimality in the knapsack soln
In this case I just assume that i is some number from a range
0,1,2,...n
"""
recon = set()
# assuming our kp soln converged, we stopped at the ith item, so
# start here and work our way backwards through all the items in
# the list of kp solns. If an item was deemed optimal by kp, then
# put it in our bag, otherwise skip it.
for j in range(0, i+1)[::-1]:
cur_val = kp_soln[j][w]
prev_val = kp_soln[j-1][w]
if cur_val > prev_val:
recon.add(j)
w = w - weight_of_item[j]
return recon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.