









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










CS 334 Analysis of Algorithms
10/18/
Carola Wenk
Slides courtesy of Charles Leiserson with changes
and additions by Carola Wenk
CS 334 Analysis of Algorithms
10/18/
Algorithm design technique (like divide and conquer)
Idea:
Do not repeatedly solve the same subproblems,
but solve them only once and store the solutions in a dynamic programming table
CS 334 Analysis of Algorithms
4
10/18/
Example:
Longest Common Subsequence (LCS)
x
m
] and
y
n
], find
a longest subsequence common to them both.
x
y
“a”
not
“the”
x
y
functional notation,but not a function
CS 334 Analysis of Algorithms
10/18/
Check every subsequence of
x
m
] to see
if it is also a subsequence of
y
n
Analysis • 2
m
subsequences of
x
(each bit-vector of
length
m
determines a distinct subsequence
of
x
CS 334 Analysis of Algorithms
10/18/
Theorem.
c
i
j
c
i
j
if
x
i
y
j
max
c
i
j
c
i
j
otherwise.
Let
z
k
x
i
y
j
]), where
c
i
j
k
. Then,
z
k
x
i
], or else
z
could be extended.
Thus,
z
k
–1] is CS of
x
i
–1] and
y
j
Proof.
Case
x
i
y
j
...
1
2
i
m
...
1
2
j
n
x
y
CS 334 Analysis of Algorithms
10/18/
Claim:
z
k
x
i
y
j
Suppose
w
is a longer CS of
x
i
–1] and
y
j
–1], that is,
w
k
–1. Then,
cut and
paste
w
z
k
w
concatenated with
z
k
]) is a
common subsequence of
x
i
] and
y
j
with
w
z
k
k
. Contradiction, proving the
claim.
Thus,
c
i
j
k
–1, which implies that
c
i
j
c
i
j
Other cases are similar.
CS 334 Analysis of Algorithms
10/18/
x
y
i
j
if
x
i
y
j
then
c
i
j
x
y
i
j
else
c
i
j
max
x
y
i–
j
x
y
i
j
Worst-case:
x
i
y
j
], in which case the
algorithm evaluates two subproblems, eachwith only one parameter decremented.
CS 334 Analysis of Algorithms
10/18/
same
subproblem
but we’re solving subproblems already solved!
m
n
3, 3,
2, 2,
1, 1,
3, 3,
3, 3,
2, 2,
1, 1,
2, 2,
Height =
m
n
work potentially exponential.
2, 2,
1, 1,
2, 2,
m
n
CS 334 Analysis of Algorithms
10/18/
There are two variants of dynamicprogramming:1. Memoization2. Bottom-up dynamic programming
(often referred to as “dynamicprogramming”)
CS 334 Analysis of Algorithms
10/18/
Memoization:
After computing a solution to a
subproblem, store it in a table. Subsequent calls checkthe table to avoid redoing work.Time =
mn
) = constant work per table entry.
Space =
mn
LCS(
x
,
y
,
i
,
j
)
if
c
[
i
,
j
] =
NIL
then if
x
[
i
] =
y
[
j
]
then
c
[
i
,
j
]
←
LCS(
x
,
y
,
i
–1,
j
–1) + 1
else
c
[
i
,
j
]
←
max
LCS(
x
,
y
,
i
–1,
j
),
LCS(
x
,
y
,
i
,
j
–1)
sameas before
for all
i
,
j
:
c
[
i
,0]=
and
c
[0,
j
]=
CS 334 Analysis of Algorithms
10/18/
DEA
Compute thetable bottom-up.
Time =
mn
CS 334 Analysis of Algorithms
10/18/
DEA
Compute thetable bottom-up.
Time =
mn
ReconstructLCS by back-tracing.
Space =
mn
Exercise: O
(min{
m
n