-2

I need to implement fractional knapsack to solve this problem

Value($} 20 50 10 90 110 70 60

Weight(lb) 3 4 1 5 6 3 4

but I'm getting confusing in how fractional knapsack work , I understand how the knapsack only work. So , in my program when I enter for example the weight limit = 7

it's gave me 143

can you help me to understand how fractional knapsack work.

Thank you

stephan
  • 37
  • 8

2 Answers2

0
  1. Sorted list in Descending order of Value / Weight is created.
  2. in your case the list will be 20/3 =6.6 , 50/4=12.75, 10/1=10,90/5=18,110/6=18.3,70/3=23.3,60/4=15
  3. Descending order : 23.3,18.3,18,15,12.5,10,6.6
  4. Weight =7.
  5. pick item 1 from Desc order list. its w=3 and 3 < 7 So Total value =0+70=70
  6. pick item 2 , w=6 ; 3+6<7? No. (so take fraction of it ) weight left=7-3=4. Parts taken=4*(18.3)=73.2 total value =70+73.2=143.2 =answer
ugola
  • 300
  • 3
  • 18
-1

The first step is to understand that the fractional knapsack problem is a greedy algorithm and therefore fulfills the greedy choice property. The property states that the first choice will be in all optimal solutions, in this case, item k with the max weight(k)/value(k) will always be taken and as much of it as possible. After understanding this concept we can move forward with the algorithm.

First Sort all the items in the backpack using weight(i)/value(i).
Then for each item in the sorted list from i=1 to n.
Take as much possible from item(i) until filled.

Note this does not work for the 0/1 knapsack problem.

Community
  • 1
  • 1