This preview shows pages 1–3. Sign up to view the full content.
Dynamic Programming
2/24/2005 1:46 AM
1
Dynamic Programming
1
Dynamic Programming
Dynamic Programming
2
Outline and Reading
Matrix ChainProduct (§5.3.1)
The General Technique (§5.3.2)
01 Knapsack Problem (§5.3.3)
Dynamic Programming
3
Matrix ChainProducts
Dynamic Programming
is a general
algorithm design paradigm.
±
Rather than give the general structure, let
us first give a motivating example:
±
Matrix ChainProducts
Review: Matrix Multiplication.
±
C
=
A
*
B
±
A
is
d × e
and
B
is
e × f
±
O
(
d
⋅
e
⋅
f
)
time
AC
B
dd
f
e
f
e
i
j
i,j
∑
−
=
=
1
0
]
,
[
*
]
,
[
]
,
[
e
k
j
k
B
k
i
A
j
i
C
Dynamic Programming
4
Matrix ChainProducts
Matrix ChainProduct:
±
Compute A=A
0
*A
1
*…*A
n1
±
A
i
is d
i
×d
i+1
±
Problem: How to parenthesize?
Example
±
B is 3 × 100
±
C is 100 × 5
±
D is 5 × 5
±
(B*C)*D takes 1500 + 75 = 1575 ops
±
B*(C*D) takes 1500 + 2500 = 4000 ops
Dynamic Programming
5
Enumeration Approach
Matrix ChainProduct Alg.:
±
Try all possible ways to parenthesize
A=A
0
*A
1
*…*A
n1
±
Calculate number of ops for each one
±
Pick the one that is best
Running time:
±
The number of parenthesizations is equal
to the number of binary trees with n nodes
±
This is
exponential
!
±
It is called the Catalan number, and it is
almost 4
n
.
±
This is a terrible algorithm!
Dynamic Programming
6
Greedy Approach
Idea #1: repeatedly select the product that
uses (up) the most operations.
Counterexample
:
±
A is 10 × 5
±
B is 5 × 10
±
C is 10 × 5
±
D is 5 × 10
±
Greedy idea #1 gives (A*B)*(C*D), which takes
500+1000+500 = 2000 ops
±
A*((B*C)*D) takes 500+250+250 = 1000 ops
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentDynamic Programming
2/24/2005 1:46 AM
2
Dynamic Programming
7
Another Greedy Approach
Idea #2: repeatedly select the product that uses
the fewest operations.
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 03/24/2010 for the course CS cs 5329 taught by Professor Wang during the Spring '10 term at Southwest Texas Junior College.
 Spring '10
 wang
 C Programming

Click to edit the document details