67ecdf0678e19_ppt
67ecdf0678e19_ppt
1
KNAPSACK PROBLEM
KNAPSACK PROBLEM
Knapsack Problem:
•A knapsack (kind of shoulder bag) with limited weight capacity.
•Few items each having some weight and value.
•The value or profit obtained by putting the items into the
knapsack is maximum.
•And the weight limit of the knapsack does not exceed.
KNAPSACK PROBLEM
If the objects are already been sorted into non-increasing order of p[i] / w[i]
then the algorithm given below obtains solutions .
Algorithm GreedyKnapsack (m, n)
// P[1 : n] and w[1 : n] contain the profits and weights respectively of
// Objects ordered so that p[i] / w[i] > p[i + 1] / w[i + 1].
// m is the knapsack size and x[1: n] is the solution vector.
{
for i 1 to n do x[i] 0.0 // initialize x
U m;
for i 1 to n do
{
if (w(i) > U) then break;
x [i] 1.0; U U – w[i];
}
if (i < n) then x[i] U / w[i];}
KNAPSACK PROBLEM
Consider the following instance of the knapsack problem: n = 3, m = 20,
(p1, p2, p3) = (25, 24, 15) and (w1, w2, w3) = (18, 15, 10).
1. First, we try to fill the knapsack by selecting the objects in some order
x1 x2 x3 wi xi pi x i
2.Select the object with the maximum profit first (p = 25). So, x 1 = 1 and profit earned is
25. Now, only 2 units of space is left, select the object with next largest profit (p = 24).
So, x2 = 2/15
x1 x2 x3 w i xi pi xi x
1 2/15 0 18 x 1 + 15 x 25 x 1 + 24 x 1
2/15 = 20 2/15 = 28.2
Example: Number of items n=3, Capacity m=45 &the weight :