The document discusses the 0/1 knapsack problem and dynamic programming algorithm to solve it. The 0/1 knapsack problem involves selecting a subset of items to pack in a knapsack that maximizes the total value without exceeding the knapsack's weight capacity. The dynamic programming algorithm solves this by building up a table where each entry represents the maximum value for a given weight. It iterates through items, checking if including each item increases the maximum value for that weight.
Dynamic Programming
It isa multistage optimizing decision
making problem closely related to “divide
& conquer” technique.
It solves the sub-problem only once &
stores the result in a table instead of
solving it recursively.
3.
0/1 Knapsack Problem
Given a set of n items and a knapsack having
capacity w, each item has weight wi and
value vi.
The problem is to pack the knapsack in such
a way so that maximum total value is
achieved and the total weight should not be
more than the fixed weight.
The problem is called 0/1 knapsack because
the items are either accepted or rejected.
4.
Algorithm
Loop, forw←0 to W(total capacity)
Set Kp[0,w] ←0.
Loop, for i ←1 to n(set of items)
Set Kp[i,0] ←0.
Check whether K is a part of solution or not-
if (wi<=w)(can be part of the solution)
if (vi+kp[i-1,w-wi])>Kp(i-1,w)
Set kp[i,w] ←vi
+kp[i-1,w-wi]
Else
Set Kp[i,w] ←Kp[i-1,w]
Exit
5.
Consider a knapsackwith weight capacity
W=3 and total items 3 such that
S=3
wi={1,2,3}
vi={2,3,4}
On applying knapsack algorithm,
Item wi
vi
1 1 2
2 2 3
3 3 4
6.
i/w 0 12 3
0
1
2
3
for w ←0 to W, for i←1 to n
Set Kp[0,w] ←0, Set Kp[i,0]←0
i/w 0 1 2 3
0 0 0 0 0
1 0
2 0
3 0
Now we havecomputed the maximum
possible values that can be taken in a
knapsack i.e Kp[n,W]
In order to select items that can take part
in making this maximum value let
i=n,k=W.
14.
Algorithm
Set i←n
setk←W
Loop to check K is a part of knapsack
while (i>0 and k>0)
if Kp[i,k]≠Kp[i-1,k] then
mark the ith item in knapsack
set i ←i-1
set k ←k-wi
Else
set i ←i-1
Exit