Explain 0/1 Knapsack Problem with example.
Question: Explain 0/1 Knapsack Problem with example.
- Knapsack problem is also called as rucksack problem.
- It is a problem in combinatorial optimization.
- Knapsack problem states that: Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.
- There are two versions of the problem:a. 0/1 Knapsack Problem: Items are indivisible; you either take an item or not. Some special instances can be solved with dynamic programming.b. Fractional knapsack problem: Items are divisible; you can take any fraction of an item.
0/1 Knapsack Problem:
i. In 0/1 Knapsack problem, items can be entirely accepted or rejected.
ii. Given a knapsack with maximum capacity W, and a set S consisting of n items.
iii. Each item i has some weight wiand benefit value bi(all wiand W are integer values).
iv. The problem is how to pack the knapsack to achieve maximum total value of packed items.
v. For solving the knapsack problem we can generate the sequence of decisions in order to obtain the optimum selection.
vi. Let Xn be the optimum sequence and there are two instances {Xn} and {Xn-1, Xn-2… X1}.
vii. So from {Xn-1, Xn-2… X1} we will choose the optimum sequence with respect to Xn.
viii. The remaining set should fulfill the condition of filling Knapsack of capacity W with maximum profit.
ix. Thus, 0/1 Knapsack problem is solved using the principle of optimality
To solve this problem using dynamic programming method we will perform following steps:
Steps:
- Let, fi (yj)be the value of optimal solution.
- Using formula:
fi(yj)=maxfi−1(y),fi−1(y−wi)+pi to solve problem. - Then Si is a pair (p, w) where
p=f(yj) andw=yj - Initially
S0=(0,0) - Then
Si1=(P,W)|(P–pi,W–wi)Si Si+11 can be computed by mergingSi and Si1 - This is used for obtaining optimal solution.
Example: Solve knapsack instance M =8 and N = 4. Let Pi= and Wi are as shown below.
i | ||
---|---|---|
1 | 1 | 2 |
2 | 2 | 3 |
3 | 5 | 4 |
4 | 6 | 5 |
Solution:
Build sequence of decision S0,S1,S2 .
Initially S0=(0,0)
This means while building S01 we select the next ith pair. For S01 we have selected first (P, W) pair which is (1, 2).
Note that the pair (3, 5) is purged from S3 . This is because, let us assume (Pj,Wj)=(3,5)and(Pk,Wk)=(5,4) , Here Pj≤Pk and Wj>Wk is true hence we will eliminate pair (Pj,Wj) i.e (3, 5) from S3
Now we are interested in M =8. We get pair (8, 8) in S4 . Hence we will set X4=1 . Now we select next object (P–P4) and (W–W4) i.e (8 - 6) and (8 - 5). i.e (2, 3) Pair (2, 3) € S2 hence set X2=1 . So we get the final solution as (0, 1, 0, 1)