0

I've got several types of coins, each have weight (wi) and cost (ci). So I've got to make a knapsack with weight==W and (!) minimum cost of coins in it. I can`t make recurrence relation to use DP.

Vesper
  • 18,599
  • 6
  • 39
  • 61
user2178460
  • 5
  • 1
  • 3

1 Answers1

1

Just formulate the usual recurrence relation...

Designate the minimum cost achievable with total weight k as Min_cost(k).

Bootstrap the memoization with:

Min_cost(0) = cost of empty set = 0

Then solve for increasing values of k using:

Min_cost(i+1) = min [Min_cost(i)   + min [ci, for all items with wi = 1],
                     Min_cost(i-1) + min [ci, for all items with wi = 2],
                     Min_cost(i-2) + min [ci, for all items with wi = 3],
                     ...
                     Min_cost(2) + min [ci, for all items with wi = w-1],
                     Min_cost(1) + min [ci, for all items with wi = w],
                     Min_cost(0) + min [ci, for all items with wi = w+1]]
Rahul Banerjee
  • 2,343
  • 15
  • 16
  • And if there is no elements with current wi, how can I find min [ci, for all items with wi = 1] in this case? And for exaple W=100 and 2 types of items: w1=1 c1=1; w2=50 c2=30, so here the answer should be 60 and I can`t get it with your algo. Can you explain your idea better? – user2178460 Mar 17 '13 at 07:51
  • If there's no item with wi = 1, you cannot have the `Min_cost(i) + min [ci, for all items with wi = 1` line in the recurrence, since those items don't exist. As for multiple coins of the same type, are there an infinite number of each? If so, the recurrence relation will choose only c1 until you compute Min_cost(50), at which point, it will switch to c2, because `Min_cost(50) = min[ Min_cost(49) + c1, Min_cost(0) + c2] = min[49 + 1, 0 + 30] = 30`. At W=90, you'll get Min_cost(100) = 60. Btw, this looks like an algorithms assignment... hope you're not using StackOverflow for homework :) – Rahul Banerjee Mar 17 '13 at 08:04