







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!








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
, 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
is
:
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
for each element A G, and add di-
rected edges
whenever it is possible for A`G
Aa to be consecutive elements in an increasing
subsequence, that is, whenever
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
c
return
k 8l a
i
i
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
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
, 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
denotes the running time of the recursive algorithm on
i
, then
g
g
f
m g
f
g
m
where
is some constant. The solution to this is
(check!), as opposed to the w
running
time of our dynamic program.
In summary, there are only
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
:
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 !
. In case (b), the remaining subproblem is to convert EXP to POL,
c
. And in
case (c), what’s left is EXP PO,
c
. In short, we have expressed
c !
as one edit, fol-
lowed one of the smaller subproblems
c !
=YEJc
Z=EJc
. We don’t know which one, so we
just try them all and take the best:
c !
=jh< t Hmc !
=YEJc
Z=EJc
.
More generally, to compute the edit distance between two words, word with letters
and word with
, we define
c
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
, let’s look at two cases. If the
letter of differs from the
letter of
, the first operation in the transformation must be one of the following
delete
, in which case
c
JT_Zs&c
f
; or
insert
, implying
c
JT_j c
f
m ; or
substitute p
, implying
c
JT_s c
f
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
f
f
m .
Therefore, we can calculate
c
as the minimum of these three possibilities! Specifically, we
can express
c
in terms of the smaller subproblems
c
f
f
mEJc
f
and
c
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 #"
, both of
which are easily solved.
c
is the fastest way to convert the
-length prefix of , namely
the empty string, to the first
letters of : clearly,
insertions. And similarly,
c
JJ%sO , for
deletions.
At this point, the algorithm for edit distance basically writes itself. For convenience, let
diff
be
if the
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
f
f
m «
=T_n>
(shown dotted in the figure), whose length is zero.
The final answer is then simply the distance between nodes
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
items to pick from, of weight ®gB
DDDm ® 9F and dollar value
ZB
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
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 ®
, or
we can look at fewer items (for instance, items
, for
). 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
, then removing this item from the knapsack should yield an optimal solution
to
!®fμ® G
. Of course, we don’t know
, so let’s try all possibilities:
´ !®
¶ k8l
G!· ¸¹!º`¸
m´ !® f»® 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
return
This algorithm fills in a one-dimensional table of length
h , in left-to-right order. Each
entry can take up to w
time to compute, so the overall running time is 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
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,
q_?N W :
maximum value achievable using a knapsack of capacity ® and items
DDDmT_
The answer we seek is
eWC .
How can we express a subproblem
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
f
mEJ´ !®
f
m=
(The first case is invoked only if ® a
® .) In other words, we can express
in terms of
subproblems
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
. Here’s the code.
Initialize all
T_Zs&% and all
J%s %
for
gh to
:
for ®
h to :
if ® a¾Á ® :
f
m
else:
T_j k8lHm´ !®
f
mEJ´ !®&f»®a
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%
Â@ÃqÉÃÊ
e Ã
ÃqÐÃ
s "
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ÃËÂ
Ãμ"D"D"HÃËÂRF , where
the ÂRG ’s are matrices with dimensions *ÑVû B
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
(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
jNq_ , we define
minimum cost of multiplying ÂÕG}ÃÂRGÓ B û"D"D"ÃÀÂza.
The size of this subproblem is the number of matrix multiplications, v
f
v. The smallest
subproblem is when
j _ , in which case there’s nothing to multiply, so
=eO#nh%
. For
,
consider the optimal subtree for t
. 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"ÃÊÂ
and Â
(^) Ó B Ão"D"D"HÃ*Âja , for some Ö
between
and
. The cost of the subtree is then the cost of these two partial products, plus
the cost of combining them: t
"D (^) a. And we just need to find the
splitting point Ö for which this is smallest:
t
JT_s× t
G!º
a
tÖ
"ª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
ph to
: t
JeO#&%
for
h to
f
:
for
h to
f
: _dO (^)
"D (^) a
return t
eWC .
The subproblems constitute a two-dimensional table, each of whose entries can take w
time
to compute. The overall running is then wt
.
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
possibilities, this strategy takes time w
. 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
.