打印背包中的麻袋

问题描述 投票:10回答:3

假设你是一个小偷,你入侵了一所房子。你在里面找到了以下物品:

一个重3磅的花瓶,价值50美元。 一块重6磅的银块,价值30美元。 一幅重4磅,价值40美元的画作。 重量为5磅,价值10美元的镜子。

这个尺寸为10磅的背包问题的解决方案是90美元。

由动态编程制成的表格是: -

现在我想知道我使用这张表放入麻袋的哪些元素然后如何回溯?

algorithm dynamic-programming knapsack-problem
3个回答
7
投票

从您的DP表我们知道f [i] [w] =总重量小于或等于w的项目1..i的子集的最大总值。

我们可以使用表本身来恢复最佳包装:

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)

0
投票

使用循环:

   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] +" ");

0
投票

我有一个受@NiklasB启发的迭代算法。当递归算法会遇到某种递归限制时,它会起作用。

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
© www.soinside.com 2019 - 2024. All rights reserved.