Professional Documents
Culture Documents
The
The 0/1
0/1 Knapsack
Knapsack Problem
Problem
&
CS404/504 Computer Science %
The
The Greedy
Greedy method
method does
does not
not work
work
for
for the
the 0/1
0/1 Knapsack
Knapsack Problem!
Problem!
&
CS404/504 Computer Science %
The
The Knapsack
Knapsack Problem
Problem
&
CS404/504 Computer Science %
0/1
0/1 Knapsack
Knapsack problem:
problem: the
the brute-force
brute-force
approach
approach
&
CS404/504 Computer Science %
Can
Can we
we do
do better?
better?
&
CS404/504 Computer Science %
Optimal
Optimal Substructure
Substructure of
of 0/1
0/1 Knapsack
Knapsack
problem
problem
• Let KNAP(1, n, M) denote the 0/1 Knapsack problem,
choosing objects from [1..n] under the capacity constraint
of M.
Proof: Cut-and-Paste.
&
CS404/504 Computer Science %
Solution
Solution in
in terms
terms of
of subproblems
subproblems
Similarly
&
CS404/504 Computer Science %
Use
Use aa table
table to
to store
store C[·,·]
C[·,·] and
and build
build it
it in
in aa
bottom
bottom upup fashion
fashion
&
CS404/504 Computer Science %
Programming
Programming =
= Table
Table
&
CS404/504 Computer Science %
Construct
Construct the
the table:
table: A
A recursive
recursive solution
solution
&
CS404/504 Computer Science %
Boundary
Boundary conditions
conditions
&
CS404/504 Computer Science %
Complete
Complete recursive
recursive formulation
formulation
&
CS404/504 Computer Science %
Algorithm
Algorithm
for i := 1 to n
for ̟ := 1 to M
if (w[i] > ̟) // cannot pick item i
C[i, ̟] := C[i - 1, ̟];
else
if ( p[i] + C[i-1, ̟ - w[i]]) > C[i-1, ̟])
C[i, ̟] := p[i] + C[i - 1, ̟ - w[i]];
else
C[i, ̟] := C[i - 1, ̟];
Complexity:
Complexity: Θ(nM
Θ(nM))
for i := 1 to n — n
for ̟ := 1 to M — M
if (w[i] > ̟)
C[i, ̟] := C[i - 1, ̟];
else
if ( p[i] + C[i-1, ̟ - w[i]]) > C[i-1, ̟])
C[i, ̟] := p[i] + C[i - 1, ̟ - w[i]];
else
C[i, ̟] := C[i - 1, ̟];
An
An example
example
n = 4 (number of items)
M = 5 (knapsack capacity = maximum weight)
(wi, pi ): (2, 3), (3, 4), (4, 5), (5, 6)
&
CS404/504 Computer Science %
Execution
Execution
&
CS404/504 Computer Science %
Compute
Compute C[2,
C[2, 5]
5]
&
CS404/504 Computer Science %
Compute
Compute C[4,
C[4, 5]
5]
&
CS404/504 Computer Science %
How
How to
to find
find the
the actual
actual items
items in
in the
the
Knapsack?
Knapsack?
• Let i = n and k = M
&
CS404/504 Computer Science %
Finding
Finding the
the items
items
&
CS404/504 Computer Science %
Solution: {1,1,
Solution: {1, 1,0,
0,0}
0}
&
CS404/504 Computer Science %