4

If you are given one set of items with values and weight: [(w1,v2),(w2,v2),...(wn,vn)], and two knapsacks Knap1 and Knap2 of equal capacity C, the goal is to determine what are the optimal subsets of items S1 and S2 that can go into Knap1 and Knap2 respectively and maximize the knapsacks' values and capacity.

An incorrect way to solve this would be to first fill Knap1 with a DP programming algorithm using all of the items as candidates, and then fill Knap2 by using the leftover items from Knap1.

I don't understand why this algorithm is incorrect if the two knapsacks have equal capacity. Could someone please explain or give an example?

Joseph D
  • 115
  • 7

2 Answers2

8

A counterexample:
Set S of items: (w_i, v_i)

   s_1=(1,2) , s_2=(2,1) , s_3=(3,10) , s_4=(4,7) 

Capacity of the Knapsacks: c_1 = c_2 = 5

Your first round of DP would take the items s_1 and s_3 which would result in value 12. Now for the second knapsack, there is s_4 and s_2 left. Thus your algorithm will choose s_4 which will result in value 7. s_2 will be left over.
Total value: 19

The optimal solutions would be s_1 and s_4 in one knapsack and s_2 and s_3 in the other. Optimal total value: 20

bro
  • 771
  • 3
  • 14
5

Suppose the capacity of the knapsacks is 10, and we have these objects (weight, value):

(8, 200) (1, 10) (1, 10) (2, 15) (9, 100)

The greedy algorithm only looking at one knapsack would use the objects of weight 8, 1 and 1 to score 220 value, but when you consider both sacks clearly leaving the 1's and taking the 2 is better.

Stef
  • 658
  • 4
  • 6
  • 'greedy' here refers to looking at only one knapsack and finding the optimal solution for that sack, without thinking about sack #2. How you find the optimal solution for the first sack (DP, or any other algorithm) is irrelevant for this answer (and the question). – Stef Jul 29 '15 at 10:58