























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!
























In the preceding chapters we have seen some elegant design principles—such as divide-and- conquer, graph exploration, and greedy choice—that yield definitive algorithms for a variety of important computational tasks. The drawback of these tools is that they can only be used on very specific types of problems. We now turn to the two sledgehammers of the algorithms craft, dynamic programming and linear programming , techniques of very broad applicability that can be invoked when more specialized methods fail. Predictably, this generality often comes with a cost in efficiency.
At the conclusion of our study of shortest paths (Chapter 4), we observed that the problem is especially easy in directed acyclic graphs (dags). Let’s recapitulate this case, because it lies at the heart of dynamic programming.
The special distinguishing feature of a dag is that its nodes can be linearized ; that is, they can be arranged on a line so that all edges go from left to right (Figure 6.1). To see why this helps with shortest paths, suppose we want to figure out distances from node S to the other nodes. For concreteness, let’s focus on node D. The only way to get to it is through its
Figure 6.1 A dag and its linearization (topological ordering).
1
2
4 1
6
3 1
2 S (^) C A B D E 4 6
3
1
2
1
1
2
170 Algorithms
predecessors, B or C; so to find the shortest path to D, we need only compare these two routes:
dist(D) = min{dist(B) + 1, dist(C) + 3}.
A similar relation can be written for every node. If we compute these dist values in the left-to-right order of Figure 6.1, we can always be sure that by the time we get to a node v, we already have all the information we need to compute dist(v). We are therefore able to compute all distances in a single pass:
initialize all dist(·) values to ∞ dist(s) = 0 for each v ∈ V {s}, in linearized order: dist(v) = min(u,v)∈E {dist(u) + l(u, v)} Notice that this algorithm is solving a collection of subproblems , {dist(u) : u ∈ V }. We start with the smallest of them, dist(s), since we immediately know its answer to be 0. We then proceed with progressively “larger” subproblems—distances to vertices that are further and further along in the linearization—where we are thinking of a subproblem as large if we need to have solved a lot of other subproblems before we can get to it. This is a very general technique. At each node, we compute some function of the values of the node’s predecessors. It so happens that our particular function is a minimum of sums, but we could just as well make it a maximum , in which case we would get longest paths in the dag. Or we could use a product instead of a sum inside the brackets, in which case we would end up computing the path with the smallest product of edge lengths.
Dynamic programming is a very powerful algorithmic paradigm in which 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 is solved. In dynamic programming we are not given a dag; the dag is implicit. Its nodes are the subproblems we define, and its edges are the dependencies between the subproblems: if to solve subproblem B we need the answer to subproblem A, then there is a (conceptual) edge from A to B. In this case, A is thought of as a smaller subproblem than B—and it will always be smaller, in an obvious sense. But it’s time we saw an example.
In the longest increasing subsequence problem, the input is a sequence of numbers a 1 ,... , an. A subsequence is any subset of these numbers taken in order, of the form ai 1 , ai 2 ,... , aik where 1 ≤ i 1 < i 2 < · · · < ik ≤ n, 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 5 , 2 , 8 , 6 , 3 , 6 , 9 , 7 is 2 , 3 , 6 , 9 :
5 2 8 6 3 6 9 7
172 Algorithms
an expression which involves only smaller subproblems. How long does this step take? It requires the predecessors of j to be known; for this the adjacency list of the reverse graph GR, constructible in linear time (recall Exercise 3.5), is handy. The computation of L(j) then takes time proportional to the indegree of j, giving an overall running time linear in |E|. This is at most O(n^2 ), the maximum being when the input array is sorted in increasing order. Thus the dynamic programming solution is both simple and efficient. There is one last issue to be cleared up: the L-values only tell us the length of the optimal subsequence, so how do we recover the subsequence itself? This is easily managed with the same bookkeeping device we used for shortest paths in Chapter 4. While computing L(j), we should also note down prev(j), the next-to-last node on the longest path to j. The optimal subsequence can then be reconstructed by following these backpointers.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 173
Returning to our discussion of longest increasing subsequences: the formula for L(j) also suggests an alternative, recursive algorithm. Wouldn’t that be even simpler? Actually, recursion is a very bad idea: the resulting procedure would require exponential time! To see why, suppose that the dag contains edges (i, j) for all i < j—that is, the given sequence of numbers a 1 , a 2 ,... , an is sorted. In that case, the formula for subproblem L(j) becomes L(j) = 1 + max{L(1), L(2),... , L(j − 1)}. The following figure unravels the recursion for L(5). Notice that the same subproblems get solved over and over again!
L(2)
L(1) L(1) L(2) L(1) L(2)
L(1) L(1) L(1) L(2)
L(1)
L(3)
L(1) L(3) L(4)
L(5)
For L(n) this tree has exponentially many nodes (can you bound it?), and so a recursive solution is disastrous.
Then why did recursion work so well with divide-and-conquer? The key point is that in divide-and-conquer, a problem is expressed in terms of subproblems that are substantially smaller , say half the size. For instance, mergesort sorts an array of size n by recursively sorting two subarrays of size n/ 2. Because of this sharp drop in problem size, the full recursion tree has only logarithmic depth and a polynomial number of nodes.
In contrast, in a typical dynamic programming formulation, a problem is reduced to subproblems that are only slightly smaller—for instance, L(j) relies on L(j − 1). Thus the full recursion tree generally has polynomial depth and an exponential number of nodes. However, it turns out that most of these nodes are repeats, that there are not too many distinct subproblems among them. Efficiency is therefore obtained by explicitly enumerating the distinct subproblems and solving them in the right order.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 175
Figure 6.3 The subproblem E(7, 5).
P O L Y N O M I A L
E X P O N E N T I A L
about looking at the edit distance between some prefix of the first string, x[1 · · · i], and some prefix of the second, y[1 · · · j]? Call this subproblem E(i, j) (see Figure 6.3). Our final objective, then, is to compute E(m, n). For this to work, we need to somehow express E(i, j) in terms of smaller subproblems. Let’s see—what do we know about the best alignment between x[1 · · · i] and y[1 · · · j]? Well, its rightmost column can only be one of three things:
x[i] − or^
y[j] or^
x[i] y[j]
The first case incurs a cost of 1 for this particular column, and it remains to align x[1 · · · i − 1] with y[1 · · · j]. But this is exactly the subproblem E(i− 1 , j)! We seem to be getting somewhere. In the second case, also with cost 1 , we still need to align x[1 · · · i] with y[1 · · · j − 1]. This is again another subproblem, E(i, j − 1). And in the final case, which either costs 1 (if x[i] 6 = y[j]) or 0 (if x[i] = y[j]), what’s left is the subproblem E(i − 1 , j − 1). In short, we have expressed E(i, j) in terms of three smaller subproblems E(i − 1 , j), E(i, j − 1), E(i − 1 , j − 1). We have no idea which of them is the right one, so we need to try them all and pick the best:
E(i, j) = min{1 + E(i − 1 , j), 1 + E(i, j − 1), diff(i, j) + E(i − 1 , j − 1)}
where for convenience diff(i, j) is defined to be 0 if x[i] = y[j] and 1 otherwise. For instance, in computing the edit distance between EXPONENTIAL and POLYNOMIAL, subproblem E(4, 3) corresponds to the prefixes EXPO and POL. The rightmost column of their best alignment must be one of the following:
O − or^
L or^
Thus, E(4, 3) = min{1 + E(3, 3), 1 + E(4, 2), 1 + E(3, 2)}.
The answers to all the subproblems E(i, j) form a two-dimensional table, as in Figure 6.4. In what order should these subproblems be solved? Any order is fine, as long as E(i − 1 , j), E(i, j − 1), and E(i − 1 , j − 1) are handled before E(i, j). For instance, we could fill in the table one row at a time, from top row to bottom row, and moving left to right across each row. Or alternatively, we could fill it in column by column. Both methods would ensure that by the time we get around to computing a particular table entry, all the other entries we need are already filled in.
176 Algorithms
Figure 6.4 (a) The table of subproblems. Entries E(i − 1 , j − 1), E(i − 1 , j), and E(i, j − 1) are needed to fill in E(i, j). (b) The final table of values found by dynamic programming.
(a)
i
j − 1 j
i − 1
m GOAL
n
(b) P O L Y N O M I A L 0 1 2 3 4 5 6 7 8 9 10 E 1 1 2 3 4 5 6 7 8 9 10 X 2 2 2 3 4 5 6 7 8 9 10 P 3 2 3 3 4 5 6 7 8 9 10 O 4 3 2 3 4 5 5 6 7 8 9 N 5 4 3 3 4 4 5 6 7 8 9 E 6 5 4 4 4 5 5 6 7 8 9 N 7 6 5 5 5 4 5 6 7 8 9 T 8 7 6 6 6 5 5 6 7 8 9 I 9 8 7 7 7 6 6 6 6 7 8 A 10 9 8 8 8 7 7 7 7 6 7 L 11 10 9 8 9 8 8 8 8 7 6
With both the subproblems and the ordering specified, we are almost done. There just remain the “base cases” of the dynamic programming, the very smallest subproblems. In the present situation, these are E(0, ·) and E(·, 0), both of which are easily solved. E(0, j) is the edit distance between the 0 -length prefix of x, namely the empty string, and the first j letters of y: clearly, j. And similarly, E(i, 0) = i. At this point, the algorithm for edit distance basically writes itself.
for i = 0, 1 , 2 ,... , m: E(i, 0) = i for j = 1, 2 ,... , n: E(0, j) = j for i = 1, 2 ,... , m: for j = 1, 2 ,... , n: E(i, j) = min{E(i − 1 , j) + 1, E(i, j − 1) + 1, E(i − 1 , j − 1) + diff(i, j)} return E(m, n)
This procedure fills in the table row by row, and left to right within each row. Each entry takes constant time to fill in, so the overall running time is just the size of the table, O(mn).
And in our example, the edit distance turns out to be 6:
178 Algorithms
Finding the right subproblem takes creativity and experimentation. But there are a few standard choices that seem to arise repeatedly in dynamic programming.
i. The input is x 1 , x 2 ,... , xn and a subproblem is x 1 , x 2 ,... , xi.
The number of subproblems is therefore linear.
ii. The input is x 1 ,... , xn, and y 1 ,... , ym. A subproblem is x 1 ,... , xi and y 1 ,... , yj.
The number of subproblems is O(mn).
iii. The input is x 1 ,... , xn and a subproblem is xi, xi+1,... , xj.
The number of subproblems is O(n^2 ).
iv. The input is a rooted tree. A subproblem is a rooted subtree.
If the tree has n nodes, how many subproblems are there?
We’ve already encountered the first two cases, and the others are coming up shortly.
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 181
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 W pounds. There are n items to pick from, of weight w 1 ,... , wn and dollar value v 1 ,... , vn. What’s the most valuable combination of items he can fit into his bag?^1 For instance, take W = 10 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 (the burglar has broken into an art gallery, say), then the optimal knapsack contains items 1 and 3 (total: $46). As we shall see in Chapter 8, neither version of this problem is likely to have a polynomial- time algorithm. However, using dynamic programming they can both be solved in O(nW ) time, which is reasonable when W is small, but is not polynomial since the input size is proportional to log W rather than W.
Let’s start with the version that allows repetition. As always, the main question in dynamic programming is, what are the subproblems? In this case we can shrink the original problem in two ways: we can either look at smaller knapsack capacities w ≤ W , or we can look at fewer items (for instance, items 1 , 2 ,... , j, for j ≤ n). It usually takes a little experimentation to figure out exactly what works. The first restriction calls for smaller capacities. Accordingly, define
K(w) = maximum value achievable with a knapsack of capacity w.
Can we express this in terms of smaller subproblems? Well, if the optimal solution to K(w) includes item i, then removing this item from the knapsack leaves an optimal solution to K(w − wi). In other words, K(w) is simply K(w − wi) + vi, for some i. We don’t know which i, so we need to try all possibilities.
K(w) = max i:wi≤w {K(w − wi) + vi},
where as usual our convention is that the maximum over an empty set is 0. We’re done! The algorithm now writes itself, and it is characteristically simple and elegant.
(^1) If this application seems frivolous, replace “weight” with “CPU time” and “only W pounds can be taken” with “only W units of CPU time are available.” Or use “bandwidth” in place of “CPU time,” etc. The knapsack problem generalizes a wide variety of resource-constrained selection tasks.
182 Algorithms
for w = 1 to W : K(w) = max{K(w − wi) + vi : wi ≤ w} return K(W )
This algorithm fills in a one-dimensional table of length W + 1, in left-to-right order. Each entry can take up to O(n) time to compute, so the overall running time is O(nW ). As always, there is an underlying dag. Try constructing it, and you will be rewarded with a startling insight: this particular variant of knapsack boils down to finding the longest path in a dag!
On to the second variant: what if repetitions are not allowed? Our earlier subproblems now become completely useless. For instance, knowing that the value K(w − wn) is very high doesn’t help us, because we don’t know whether or not item n already got used up in this partial solution. We must therefore refine our concept of a subproblem to carry additional information about the items being used. We add a second parameter, 0 ≤ j ≤ n:
K(w, j) = maximum value achievable using a knapsack of capacity w and items 1 ,... , j.
The answer we seek is K(W, n). How can we express a subproblem K(w, j) in terms of smaller subproblems? Quite simple: either item j is needed to achieve the optimal value, or it isn’t needed:
K(w, j) = max{K(w − wj , j − 1) + vj , K(w, j − 1)}.
(The first case is invoked only if wj ≤ w.) In other words, we can express K(w, j) in terms of subproblems K(·, j − 1). The algorithm then consists of filling out a two-dimensional table, with W + 1 rows and n + 1 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, O(nW ). Here’s the code.
Initialize all K(0, j) = 0 and all K(w, 0) = 0 for j = 1 to n: for w = 1 to W : if wj > w: K(w, j) = K(w, j − 1) else: K(w, j) = max{K(w, j − 1), K(w − wj , j − 1) + vj } return K(W, n)
184 Algorithms
Figure 6.6 A × B × C × D = (A × (B × C)) × D.
(a)
× ×
A B C D
×
50 × 20 20 × 1 1 × 10 10 × 100
(b)
×
A B × C
×
50 × 20 20 × 10
D 10 × 100
(c)
A × (B × C)
×
50 × 10
D 10 × 100
(d)
(A × (B × C)) × D 50 × 100
Suppose that we want to multiply four matrices, A × B × C × D, of dimensions 50 × 20 , 20 × 1 , 1 × 10 , and 10 × 100 , respectively (Figure 6.6). This will involve iteratively multiplying two matrices at a time. Matrix multiplication is not commutative (in general, A×B 6 = B×A), but it is associative , which means for instance that A × (B × C) = (A × B) × C. Thus we can compute our product of four matrices in many different ways, depending on how we parenthesize it. Are some of these better than others? Multiplying an m × n matrix by an n × p matrix takes mnp multiplications, to a good enough approximation. Using this formula, let’s compare several different ways of evaluating A × B × C × D:
Parenthesization Cost computation Cost A × ((B × C) × D) 20 · 1 · 10 + 20 · 10 · 100 + 50 · 20 · 100 120 , 200 (A × (B × C)) × D 20 · 1 · 10 + 50 · 20 · 10 + 50 · 10 · 100 60 , 200 (A × B) × (C × D) 50 · 20 · 1 + 1 · 10 · 100 + 50 · 1 · 100 7 , 000
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 A 1 × A 2 × · · · × An, where the Ai’s are matrices with dimensions m 0 × m 1 , m 1 × m 2 ,... , mn− 1 × mn, 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
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 185
Figure 6.7 (a) ((A × B) × C) × D; (b) A × ((B × C) × D); (c) (A × (B × C)) × D.
D A
C
A B
D
B C
D
A
B C
(a) (b) (c)
product, and interior nodes are intermediate products (Figure 6.7). The possible orders in which to do the multiplication correspond to the various full binary trees with n leaves, whose number is exponential in n (Exercise 2.13). We certainly cannot try each tree, and with brute force thus ruled out, we turn to dynamic programming.
The binary trees of Figure 6.7 are suggestive: for a tree to be optimal, its subtrees must also be optimal. What are the subproblems corresponding to the subtrees? They are products of the form Ai × Ai+1 × · · · × Aj. Let’s see if this works: for 1 ≤ i ≤ j ≤ n, define
C(i, j) = minimum cost of multiplying Ai × Ai+1 × · · · × Aj.
The size of this subproblem is the number of matrix multiplications, |j − i|. The smallest subproblem is when i = j, in which case there’s nothing to multiply, so C(i, i) = 0. For j > i, consider the optimal subtree for C(i, j). The first branch in this subtree, the one at the top, will split the product in two pieces, of the form Ai × · · · × Ak and Ak+1 × · · · × Aj , for some k between i and j. The cost of the subtree is then the cost of these two partial products, plus the cost of combining them: C(i, k) + C(k + 1, j) + mi− 1 · mk · mj. And we just need to find the splitting point k for which this is smallest:
C(i, j) = min i≤k<j
{C(i, k) + C(k + 1, j) + mi− 1 · mk · mj }.
We are ready to code! In the following, the variable s denotes subproblem size.
for i = 1 to n: C(i, i) = 0 for s = 1 to n − 1 : for i = 1 to n − s: j = i + s C(i, j) = min{C(i, k) + C(k + 1, j) + mi− 1 · mk · mj : i ≤ k < j} return C(1, n)
The subproblems constitute a two-dimensional table, each of whose entries takes O(n) time to compute. The overall running time is thus O(n^3 ).
S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 187
What if we want to find the shortest path not just between s and t but between all pairs of vertices? One approach would be to execute our general shortest-path algorithm from Section 4.6.1 (since there may be negative edges) |V | times, once for each starting node. The total running time would then be O(|V |^2 |E|). We’ll now see a better alternative, the O(|V |^3 ) dynamic programming-based Floyd-Warshall algorithm. Is there is a good subproblem for computing distances between all pairs of vertices in a graph? Simply solving the problem for more and more pairs or starting points is unhelpful, because it leads right back to the O(|V |^2 |E|) algorithm. One idea comes to mind: the shortest path u → w 1 → · · · → wl → v between u and v uses some number of intermediate nodes—possibly none. Suppose we disallow intermediate nodes altogether. Then we can solve all-pairs shortest paths at once: the shortest path from u to v is simply the direct edge (u, v), if it exists. What if we now gradually expand the set of permissible intermediate nodes? We can do this one node at a time, updating the shortest path lengths at each stage. Eventually this set grows to all of V , at which point all vertices are allowed to be on all paths, and we have found the true shortest paths between vertices of the graph! More concretely, number the vertices in V as { 1 , 2 ,... , n}, and let dist(i, j, k) denote the length of the shortest path from i to j in which only nodes { 1 , 2 ,... , k} can be used as interme- diates. Initially, dist(i, j, 0) is the length of the direct edge between i and j, if it exists, and is ∞ otherwise. What happens when we expand the intermediate set to include an extra node k? We must reexamine all pairs i, j and check whether using k as an intermediate point gives us a shorter path from i to j. But this is easy: a shortest path from i to j that uses k along with possibly other lower-numbered intermediate nodes goes through k just once (why? because we assume that there are no negative cycles). And we have already calculated the length of the shortest path from i to k and from k to j using only lower-numbered vertices:
Thus, using k gives us a shorter path from i to j if and only if
dist(i, k, k − 1) + dist(k, j, k − 1) < dist(i, j, k − 1),
in which case dist(i, j, k) should be updated accordingly. Here is the Floyd-Warshall algorithm—and as you can see, it takes O(|V |^3 ) time.
for i = 1 to n: for j = 1 to n: dist(i, j, 0) = ∞
188 Algorithms
Figure 6.9 The optimal traveling salesman tour has length 10.
2
2
2
3
4
2
4
2
1 3
for all (i, j) ∈ E: dist(i, j, 0) = `(i, j) for k = 1 to n: for i = 1 to n: for j = 1 to n: dist(i, j, k) = min{dist(i, k, k − 1) + dist(k, j, k − 1), dist(i, j, k − 1)}
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 1 ,... , n, the salesman’s hometown being 1 , and let D = (dij ) be the matrix of intercity distances. The goal is to design a tour that starts and ends at 1 , includes all other cities exactly once, and has minimum total length. Figure 6.9 shows an 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 Chapter 8, 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 (n − 1)! possibilities, this strategy takes O(n!) time. 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 j. What