Docsity

Lecture Notes on Dynamic Programming - Design and Analysis Algorithm | CS 3510, Study notes of Algorithms and Programming

Toggle sidebar
bg1
Dynamic Programming
1 Shortest paths in dags, revisited
At the conclusion of our study of shortest paths, we observed that the problem is especially
easy in directed acyclic graphs (dags). Let’s recapitulate this case, because it lies close to the
heart of dynamic programming.
The special distinguishing feature of a dag is that its nodes can be topologically ordered,
that is, they can be arranged on a line so that all edges go from left to right (Figure 1.1). To
see why this helps with shortest paths, suppose we want to figure out distances from node
to the other nodes in the figure. For concreteness, let’s focus on node
. The only way to get to
it is through its predecessors,
or
; so to find the shortest path to
, we need only compare
these two routes:
dist

dist


dist


A similar relation can be written for every node. These are simple formulas, but they are
recursive, and a recursive implementation would be disastrously inefficient (Exercise). Here’s
where the topological ordering comes in: if we compute these dist values in the left-to-right
order of Figure 1.1, we can always be sure that by the time we get to a node
, we already
have the other information we need to compute dist
!
. We are therefore able to compute all
distances in a single pass:
initialize all dist
#"
values to
$
dist
&%
for each
('*),+
, in topological order:
dist
!
-.0/21 3546879
dist
!:
<;
!:
=
Notice that this algorithm is solving a collection of subproblems,
dist
!:
?>
:@'@)
. We
start with the smallest of them, dist
, since we immediately know its answer to be zero.
We then proceed with progressively “larger” subproblems, where we think of a subproblem as
large if it is far along in the topological ordering, that is, if we need to have solved a lot of
other subproblems before we can get to it.
Dynamic programming is a very powerful algorithmic paradigm which is a generalization
of this strategy: a problem is solved by identifying a collection of subproblems and tackling
them one-by-one, smallest first, using the answers to small problems to help figure out larger
ones, until the whole lot of them are solved.
Figure 1.1 A dag and its topological ordering.
B
D
C
A
S E
1
2
41
6
31
2
SCAB D E
2
4
16
3
1
2
1
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Lecture Notes on Dynamic Programming - Design and Analysis Algorithm | CS 3510 and more Study notes Algorithms and Programming in PDF only on Docsity!

Dynamic Programming

1 Shortest paths in dags, revisited

At the conclusion of our study of shortest paths, we observed that the problem is especially

easy in directed acyclic graphs (dags). Let’s recapitulate this case, because it lies close to the

heart of dynamic programming.

The special distinguishing feature of a dag is that its nodes can be topologically ordered ,

that is, they can be arranged on a line so that all edges go from left to right (Figure 1.1). To

see why this helps with shortest paths, suppose we want to figure out distances from node

to the other nodes in the figure. For concreteness, let’s focus on node

. The only way to get to

it is through its predecessors,  or  ; so to find the shortest path to

, we need only compare

these two routes:

dist 

dist ^

dist ^

A similar relation can be written for every node. These are simple formulas, but they are

recursive, and a recursive implementation would be disastrously inefficient (Exercise). Here’s

where the topological ordering comes in: if we compute these dist values in the left-to-right

order of Figure 1.1, we can always be sure that by the time we get to a node , we already

have the other information we need to compute dist !

. We are therefore able to compute all

distances in a single pass:

initialize all dist #"

values to $

dist

for each ('*),+

, in topological order:

dist !

dist !:

Notice that this algorithm is solving a collection of subproblems ,

dist !:

. We

start with the smallest of them, dist 

, since we immediately know its answer to be zero.

We then proceed with progressively “larger” subproblems, where we think of a subproblem as

large if it is far along in the topological ordering, that is, if we need to have solved a lot of

other subproblems before we can get to it.

Dynamic programming is a very powerful algorithmic paradigm which is a generalization

of this strategy: a problem is solved by identifying a collection of subproblems and tackling

them one-by-one, smallest first, using the answers to small problems to help figure out larger

ones, until the whole lot of them are solved.

Figure 1.1 A dag and its topological ordering.

B

C D

A

S E

1

2

4 1

6

3 1

2

S (^) C A B D E

2

1 4 6

3

1

2

1

Figure 2.1 The dag of increasing subsequences.

5 2 8 6 3 6 9 7

2 Longest increasing subsequences

[Connections: statistical tests for pseudorandomness; card games.]

In the longest increasing subsequence problem, the input is a sequence of numbers ACB"D"D"EAF.

A subsequence is any subset of these numbers taken in order, something of the form AHG!IJAGLKC"D"D"=AGM

where

,NPO

B

RQ

O

TS

Q

@"D"D"HQ

O

TUVNW

, and an increasing subsequence is one in which the numbers

are getting strictly larger. The task is to find the increasing subsequence of greatest length.

For instance, the longest increasing subsequence of X

=YZ=[Z=\Z=Z=\Z=]ZE^

is

Y

Z=Z=\Z=]

:

5 2 8 6 3 6 9 7

In this little example, the arrows above denote transitions between consecutive elements

in the optimal solution. More generally, to better understand the solution space, let’s create

a graph of all permissible transitions: establish a node

O

for each element A G, and add di-

rected edges 

O

JT_Z

whenever it is possible for A`G

Aa to be consecutive elements in an increasing

subsequence, that is, whenever

O

Q

_

and A G QPA a (Figure 2.1).

Notice that (1) this graph b

Jcd is a dag, since it respects the topological ordering =YZDDD8eW , and (2) there is a one-to-one correspondence between increasing subsequences and

paths in this dag. Therefore, our goal is simply to find the longest path in the dag! This is

easy to do, by setting edge lengths to f

and finding the shortest path.

Here is a more direct rendition of the same algorithm:

for

_

gh=YZDDD8eW : i 

_hj< k8lHmi 

O#9>

OJT_

c 

return

k 8l a

i 

_Z

i 

_Z

is the length of the longest path ending at

_

(plus one, since strictly speaking we need

to count nodes on the path, not edges). By reasoning in the same way as we did for shortest

paths, we see that any path to node

_

must pass through one of its predecessors, and therefore i 

_Z

is one plus the maximum

i #"

value of these predecessors. If there are no edges into

_

,

we take the maximum over the empty set, zero. And the final answer is the largest

i 

_

Z

, since

any ending position is allowed.

This is dynamic programming. In order to solve our original problem, we have defined a

collection of subproblems

mi 

n>,No(NWp with the following key property that allows them

to be solved in a single pass:

If ‚g

W

C

denotes the running time of the recursive algorithm on

i 

W

C

, then

‚g

W

C}

g

W

f

m ‚ g

W

f

Y

D"D"

‚g

mƒ „†

where

is some constant. The solution to this is

Y

F

(check!), as opposed to the w 

W

S

running

time of our dynamic program.

In summary, there are only

W

subproblems, but a naive recursive scheme ends up recom-

puting some of them exponentially many times. On the other hand, dynamic programming

exploits a natural ordering amongst these subproblems, and solves each of them just once.

Programming? (boxed)

The origin of the term dynamic programming has very little to do with writing

code. It was first coined by Richard Bellman in the 1950s, a time when computer

programming was an esoteric activity practiced by so few people as to not even merit a

name. Back then “programming” meant “planning”, and “dynamic programming” was

used to optimally plan a multi-stage process. The dag of Figure 2.1 can be thought of

as describing the possible ways in which such a process can evolve: each node denotes

a state, the leftmost node is the starting point, and the edges leaving a state represent

possible actions, leading to different states in the next unit of time.

The etymology of linear programming , the subject of the next chapter, is similar.

3 Edit distance

When a spell checker encounters a possible misspelling, it looks up its dictionary for other

words that are close by. What is the appropriate notion of closeness in this case?

A very natural measure of distance between strings ‡ and ˆ is the minimum number of

edits — insertions, deletions, and substitutions of characters — needed to transform ‡ into ˆ.

For instance, the edit distance between to and fro is

Y

:

f Œ Ž

(substitution) fŒ Ž

(insertion)

(and clearly one edit isn’t enough to do the job). Notice that edit distance is symmetric , in the

sense that it doesn’t depend on the order of its two arguments.

Let’s figure out how to compute this distance.

A dynamic programming solution

When solving a problem by dynamic programming, the most crucial question is, what are the

subproblems? As long as they are chosen so as to have the property (*) we discussed earlier,

it is an easy matter to write down the algorithm: iteratively solve one subproblem after the

other, in order of increasing size.

Our goal is to find the edit distance of two strings, say EXPONENTIAL and POLYNOMIAL.

What is a good subproblem? Well, it should go part of the way towards converting one string

to the other; so how about looking at the smallest number of edits needed to transform some

prefix of the first string, such as EXPO, into some prefix of the second, say POL?

This is certainly plausible, but we also need to express large subproblems in terms of

smaller ones. Let’s think.

The edit distance between EXPO and POL, call it

c !

, is the number of edits needed to

convert the first string into the second one. There are many ways to perform this transforma-

tion. We could start at the left-hand side of EXPO and systematically move right, gradually

converting to POL as we go along:

EXPO – XPO (delete E) – PO (delete X) – POL (insert L).

Or we could move right-to-left, so that the next edit is always at the rightmost unmatched

position of the source string:

EXPO – EXPOL (insert L) – EPOL (delete X) – POL (delete E).

Or equally, middle-out. What should we do?

Right-to-left seems the best strategy: if we can at least partially align the rightmost char-

acters of the two strings, we should then be able to fall back on smaller subproblems like

EXPŒ POL or EXPŒ PO. Now, given that the first edit will be at right end of EXPO, there are

only three things it can be:

(a) insert L; (b) delete O; (c) substitute O Œ L.

In the first case, the remaining edits must convert EXPO to PO, which we would call subprob-

lem

c !

=Y

. In case (b), the remaining subproblem is to convert EXP to POL,

c 

Z=

. And in

case (c), what’s left is EXPŒ PO,

c 

Z=Y

. In short, we have expressed

c !

as one edit, fol-

lowed one of the smaller subproblems

c !

=YEJc 

Z=EJc 

Z=Y‘

. We don’t know which one, so we

just try them all and take the best:

c !

=jh’< t  Hmc  !

=YEJc 

Z=EJc 

Z=Y‘=

.

More generally, to compute the edit distance between two words, word ‡ with “ letters

and word ˆ with

W

, we define

c 

O

JT_

to be the edit distance between the prefixes ‡•”

pDD=O– and

ˆ”

pDD#_–

. Obviously, our final objective is to compute

c !“

eWC .

To figure out

c 

O

JT_

, let’s look at two cases. If the

O

letter of ‡ differs from the

_

letter of

ˆ , the first operation in the transformation must be one of the following

delete ‡•”

O

, in which case

c 

O

JT_Zs&c 

O

f

T_&

; or

insert ˆœ”

_

, implying

c 

O

JT_j c 

OJT_

f

mƒ  ; or

substitute ‡p”

O

_

, implying

c 

O

JT_s c 

O

f

T_

f

mƒ  .

On the other hand, if the end characters of the two prefixes match, the first two options above

remain legitimate, but for the third there is no increase in edit distance. It becomes

š c 

OJT_j c 

O

f

T_

f

m .

Therefore, we can calculate

c 

O

JT_

as the minimum of these three possibilities! Specifically, we

can express

c 

O

JT_

in terms of the smaller subproblems

c 

O

f

T_

f

mEJc 

O

f

T_E

and

c 

O

JT_

f

m .

We are almost done. There just remain the “base cases” of the dynamic programming,

the very smallest subproblems. In the present situation, these are

c 

and

c #"

J%‘

, both of

which are easily solved.

c 

žT_

is the fastest way to convert the

-length prefix of ‡ , namely

the empty string, to the first

_

letters of ˆ: clearly,

_

insertions. And similarly,

c 

O

JJ%‘sO , for

O

deletions.

At this point, the algorithm for edit distance basically writes itself. For convenience, let

diff 

O

JT_

be

if the

O

T—™

letter of ‡ differs from the

_

letter of ˆ ,

otherwise.

In fact, we can take things a little further and put weights on the edges so that the edit

distances are given by shortest paths in the dag! To see this, set all edge lengths to one,

except for

O

f

T_

f

m Œ «

O

=T_n> ‡ •”

O

_

(shown dotted in the figure), whose length is zero.

The final answer is then simply the distance between nodes

žJ%‘

and ¬

eWC

. One

possible shortest path is shown, the one that yields the alignment we found earlier. On this

path, each move down is a deletion, each move right is an insertion, and each diagonal move

is either a match or a substitution.

By altering the weights on this dag, we can allow generalized forms of edit distance, in

which insertions, deletions and substitutions have different associated costs.

4 Knapsack

Consider the following scenario: during a robbery, a burglar finds much more loot than he

had expected and has to decide what to take. His bag (or “knapsack”) will hold a total weight

of at most pounds. There are

W

items to pick from, of weight ®gB

DDDm ® 9F and dollar value

ZB

DDDª

F. What’s the most valuable combination of items he can fit into his bag? 2

For instance, take

hD% and

Item Weight Value

1 6 $

2 3 $

3 4 $

4 2 $

There are two versions of this problem. If there are unlimited quantities of each item avail-

able, the optimal choice is to pick item 1 and two of item 4 (total: $ 48). On the other hand, if

there is one of each item, then the optimal knapsack contains items 1 and 3 (total: $46).

As we shall see a few chapters down the line, neither version of this problem is likely to

have a polynomial-time algorithm. However, using dynamic programming they can both be

solved in w 

W

time, which is reasonable when is small, but is not polynomial since the

input size is proportional to ¯L°2±9 , not.

Let’s start with the version which allows repetition. As always, the main question in

dynamic programming is, what are the subproblems? Well, in this case we can shrink the

original problem in two ways: we can either look at smaller knapsack capacities ®

N

, or

we can look at fewer items (for instance, items

=YZDDD†T_

, for

_

²N³W

). It usually takes a little

experimentation to figure out exactly what works.

The first restriction calls for smaller capacities. Accordingly, define

´ !®

maximum value achievable with a knapsack of capacity ®

Can we express this in terms of smaller subproblems? Well, if the optimal solution to

includes item

O

, then removing this item from the knapsack should yield an optimal solution

to

!®fμ® G

. Of course, we don’t know

O

, so let’s try all possibilities:

´ !®

¶ k8l

G!· ¸¹!º`¸

m´  !® f»® G

G

2 If this application seems frivolous, replace “weight” with “CPU time” and “only ¼ pounds can be taken”

with “only ¼ units of CPU time are available”. Or bandwidth instead of CPU time, etc. The knapsack problem

generalizes a wide variety of resource-constrained selection tasks.

where as usual our convention is that the maximum over an empty set is zero. We’re done!

The algorithm now writes itself, and it is characteristically simple and elegant.

´ 

for ®

h to : ´ !®

’ k8lHm´  !®&f²®9G

G

®9G

N

return

This algorithm fills in a one-dimensional table of length

h , in left-to-right order. Each

entry can take up to w 

W

C

time to compute, so the overall running time is w 

W

. As always,

we can also construct the underlying dag. Doing so gives us a startling insight: this particular

variant of knapsack is nothing other than longest path in a dag! (Check!)

Onto the second variant: what if repetitions are not allowed? Our earlier subproblems

now become completely useless. For instance, knowing that the value

½f®¾F^

(^) is very high

doesn’t help us, because we don’t know whether or not item

W

already got used up in this

partial solution. Our subproblems therefore need to carry additional information about the

items being used. We add a second parameter,

N

q_?N W :

T_Z’

maximum value achievable using a knapsack of capacity ® and items

DDDmT_

The answer we seek is

eWC .

How can we express a subproblem

T_

in terms of smaller subproblems? Quite simple:

either item

_

is needed to achieve the optimal value, or it isn’t needed:

T_Z’ tk8lHm´  !® f»®’a

T_

f

mEJ´  !®

T_

f

m=

(The first case is invoked only if ® a

N

® .) In other words, we can express

T_

in terms of

subproblems

T_

f

m .

The algorithm then consists of filling out a two-dimensional table, with

rows and WÀ¿ columns. Each table entry takes just constant time, so even though the table is much

larger than in the previous case, the running time remains the same, w 

W

. Here’s the code.

Initialize all

žT_Zs&% and all

J%‘s %

for

_

gh to

W

:

for ®

h to :

if ® a¾Á ® :

T_Z’ ´

T_

f

m

else:

T_j k8lHm´  !®

T_

f

mEJ´  !®&f»®’a

T_

f

m=

return

eWC

Figure 5.1 (i) e¿ÃË

Ã*

Ã

; (ii) ¿ÃqeÎÃÊ

Ã

Å

; (iii) ÂhÃqÉÃÊ

e Ã

.

D A

C

A B

D

B C

D

A

B C

¿ÃÀÉÃÊÄÃ

:

Parenthesization Cost computation Cost

Â@ÃqeÉÃÊ

Ã

 Y%

D%R

Y%

D%

D%2%Ï

X

Y%

D%2% ªY%ž=Y%2%

Â@ÃqÉÃÊ

e Ã

 Y%

D%Ï

X

Y%

D%Ï

X

D%

D%2% \%ž=Y%2%

Â@ÃÀ

ÃqÐÃ

X

Y%

s  "

D%

D%2%Ï

X

D%2% ^J%2%2%

As you can see, the order of multiplications makes a big difference in the final running time!

Moreover, the natural greedy approach, to always perform the cheapest matrix multiplication

available, leads to the second parenthesization shown here, and is therefore a failure.

How do we determine the optimal order, if we want to compute  BRÃËÂ

S

Ãμ"D"D"HÃËÂRF , where

the ÂRG ’s are matrices with dimensions “*ÑVû“ B

“ B û“

S

DDDm “ F ÒB û“ F , respectively? The

first thing to notice is that a particular parenthesization can be represented very naturally by

a binary tree in which the individual matrices correspond to the leaves, the root is the final

product, and interior nodes are intermediate products (Figure 5.1). The number of possible

orders in which to do the multiplication is therefore equal to the number of binary trees with W leaves, which is exponential in

W

(check!). We certainly cannot try each tree, and with brute

force thus ruled out, we turn to dynamic programming.

The binary trees of Figure 5.1 are suggestive: for a tree to be optimal, its subtrees must

also be optimal. What are the subproblems corresponding to subtrees? They are products of

the form  G ÃÀ GÓ BÔû"D"D"ÃÀ a. Let’s see if this works. For

O

jNq_ , we define

OJT_Z’

minimum cost of multiplying ÂÕG}ÃÂRGÓ B û"D"D"ÃÀÂza.

The size of this subproblem is the number of matrix multiplications, v

_

f

O

v. The smallest

subproblem is when

O

j _ , in which case there’s nothing to multiply, so  

O

=eO#nh%

. For

_

Á

O

,

consider the optimal subtree for t

O

JT_

. The first branch in this subtree, the one at the top,

will split the product in two pieces, of the form ¾GÃo"D"D"ÃÊÂ

U

and Â

U

(^) Ó B Ão"D"D"HÃ*Âja , for some Ö

between

O

and

_

. The cost of the subtree is then the cost of these two partial products, plus

the cost of combining them: t

O

J

Ö

›Ö

T_Zƒ

G

Ò

B}"D“

U

"D“ (^) a. And we just need to find the

splitting point Ö for which this is smallest:

t

O

JT_s× t 

G!º

U

†Ø

a

O

Ö

t›Ö

T_C

G ÒB "D“

U

"ª“ta

s

We are ready to code! In the following, the variable

denotes subproblem size.

Figure 6.1 The optimal traveling salesman tour has length ten.

B

C D

A

E

2

2

2

3

4

2

4

2

1

3

for

O

ph to

W

: t

O

JeO#&%

for

h to

W

f

:

for

O

•h to

W

f

: _dOœ (^)

O=T_’&  H

O=

Ö

›Ö

T_C

G

Ò

B"D“

U

"D“ (^) a

‘O’N

Ö

Q

_

return t

eWC .

The subproblems constitute a two-dimensional table, each of whose entries can take w 

W

C

time

to compute. The overall running is then wt

W

•Ùª

.

6 The traveling salesman problem

A traveling salesman is getting ready for a big sales tour. Starting at his hometown, suitcase

in hand, he will conduct a journey in which each of his target cities is visited exactly once

before he returns home. Given the pairwise distances between cities, what is the best order

in which to visit them, so as to minimize the overall distance traveled?

Denote the cities by

DDDmeW , the salesman’s hometown being

, and let

Ú

Û Ga

be the

matrix of intercity distances. The goal is to design a tour which starts and ends at 1, includes

all other cities exactly once, and has minimum total length. Figure 6.1 shows a example

involving five cities. Can you spot the optimal tour? Even in this tiny example, it is tricky for

a human to find the solution; imagine what happens when hundreds of cities are involved.

It turns out this problem is also difficult for computers. In fact, the traveling salesman

problem (TSP) is one of the most notorious computational tasks. There is a long history of

attempts at solving it, a long saga of failures and partial successes, and along the way, major

advances in algorithms and complexity theory. The most basic piece of bad news about the

TSP, which we will better understand in a couple of chapters, is that it is highly unlikely to

be solvable in polynomial time.

How long does it take, then? Well, the brute-force approach is to evaluate every possible

tour and return the best one. Since there are

W

}Ü

possibilities, this strategy takes time w 

W

W}Ü0

. We will now see that dynamic programming yields a much faster solution, though not a

polynomial one.

What is the appropriate subproblem for the TSP? Subproblems refer to partial solutions,

and in this case the most obvious partial solution is the initial portion of a tour. Suppose

we have started at city 1, as required, have visited a few cities, and are now in city

_

. What

information do we need in order to extend this partial tour? We certainly need to know

_

, since

this will determine which cities are most convenient to visit next. And we also need to know

Figure 7.

é !:

is the size of the largest independent set of the subtree rooted at :. Two cases:

either : is in this independent set, or it isn’t.

u

r

Our final goal is

é !è

.

Dynamic programming proceeds as always from smaller subproblems to larger ones, that

is to say, bottom-up in the rooted tree. Suppose we know the largest independent sets for all

subtrees below a certain node : ; in other words, suppose we know

é !®

for all descendants ®

of :. How can we compute

é !:

? Let’s split the computation into two cases: any independent

set either includes : or it doesn’t (Figure 7.2).

é !:

qÌ tk8l

ê ë ßì  j í

grandchildren î of ï

é  !®

E í

children î of ï

é  !®

2ðßñ

ò

If the independent set includes : , then we get one point for it, but we aren’t allowed to include

the children of : – therefore we move onto the grandchildren. This is the first case in the

formula. On the other hand, if we don’t include : , then we don’t get a point for it, but we can

move on to its children.

The number of subproblems is exactly the number of vertices. With a little care, the

running time can be made linear, w Jvß)(v

v

c v

.