Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
A silver nugget that weights 6 pounds and is worth 30 dollars.
A painting that weights 4 pounds and is worth 40 dollars.
A mirror that weights 5 pounds and is worth 10 dollars.

Solution to this Knapsack problem of size 10 pounds is 90 dollars .

Table made from dynamic programming is :-

enter image description here

Now i want to know which elements i put in my sack using this table then how to back track ??

like image 582
T.J. Avatar asked Apr 20 '14 18:04

T.J.


People also ask

How to print the items in 0 by 1 knapsack?

Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively.

How 0 1 knapsack problem can be solved using backtracking design strategy?

It takes θ(nw) time to fill (n+1)(w+1) table entries. It takes θ(n) time for tracing the solution since tracing process traces the n rows. Thus, overall θ(nw) time is taken to solve 0/1 knapsack problem using dynamic programming.


1 Answers

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.

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)
like image 163
Niklas B. Avatar answered Sep 30 '22 08:09

Niklas B.