Professional Documents
Culture Documents
21 Knapsack Problem
21 Knapsack Problem
1
Knapsack Problem
You are given the following-
• A knapsack - with limited weight capacity.
• items - having some weight and value.
4kg 8kg
$2 $17
3
0/1 Knapsack Problem
In 0/1 Knapsack Problem,
• As the name suggests, items are indivisible here.
• We can not take the fraction of any item.
• We have to either take an item completely or leave it completely.
Example:
Consider the knapsack instance n = 3, (w1, w2, w3) = (2, 3, 4), (p1, p2, p3) = (1, 2, 5) and m
= 6.
Probability of Chosen Items (xi) = [{0, 0, 0}, {0, 0, 1}, ……, {1, 1, 1}]
4
0/1 Knapsack Problem – Solution: Set Method
Initially S0 = {(0,0)}
Purging or dominance rule: if Si+1 contains two pairs (pj, wj ) and (pk, wk ) with the
When generating Si, we can also purge all pairs ( p, w ) with w > m as these pairs
determine the value of f n (x) only for x > m.
Therefore ,
S3 ={(0,0)(1,2)(2,3)(5,4)(6,6)}
To find the included items:
(6,6) is in S3 So x3 = 1
(1,2) is in S1 So x1=1
Therefore X=(1,0,1) 7
0/1 Knapsack Algorithm
Algorithm DKP(p,w,n,m)
{
S0 := {(0,0)};
for i := 1 to n-1 do
{
Si-1 ={(P,W)|(P-pi ,W-wi ) ϵ Si-1 and W <= m);
Si = MergePurge(Si-1 , S1i-1);
}
(PX,WX) = last pair in Sn-1 ;
(PY,WY)=(P1+ pn ,W1+wn ) where W1 is the largest W in any pair in Sn-1 such that
W+ wn <= m;
8
// Trace back for xn ,xn-1,…..,x1.
if (PX > PY) then
xn = 0;
else xn=1;
TraceBackFor(xn-1,…..,x1);
}
Complexity Analysis:
The complexity of the algorithm is O(nW) where, n is the number of items and W
is the capacity of knapsack.
9
10
11
Example 3:
12
Thank You