Docsity

Introduction to Algorithms, Lecture Notes - Computer Science - 6, Study notes of Introduction to Computers

Toggle sidebar
bg1
Chapter 5
Greedy algorithms
A game like chess can be won only by thinking ahead: a player who is focused entirely on
immediate advantage is easy to defeat. But in many other games, such as Scrabble, it is
possible to do quite well by simply making whichever move seems best at the moment and not
worrying too much about future consequences.
This sort of myopic behavior is easy and convenient, making it an attractive algorithmic
strategy. Greedy algorithms build up a solution piece by piece, always choosing the next
piece that offers the most obvious and immediate benefit. Although such an approach can be
disastrous for some computational tasks, there are many for which it is optimal. Our first
example is that of minimum spanning trees.
5.1 Minimum spanning trees
Suppose you are asked to network a collection of computers by linking selected pairs of them.
This translates into a graph problem in which nodes are computers, undirected edges are
potential links, and the goal is to pick enough of these edges that the nodes are connected.
But this is not all; each link also has a maintenance cost, reflected in that edge’s weight. What
is the cheapest possible network?
A
B
C
D
E
F
4
1
4
3425
6
4
One immediate observation is that the optimal set of edges cannot contain a cycle, because
removing an edge from this cycle would reduce the cost without compromising connectivity:
Property 1
Removing a cycle edge cannot disconnect a graph.
So the solution must be connected and acyclic: undirected graphs of this kind are called
trees. The particular tree we want is the one with minimum total weight, known as the
minimum spanning tree. Here is its formal definition.
139
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Introduction to Algorithms, Lecture Notes - Computer Science - 6 and more Study notes Introduction to Computers in PDF only on Docsity!

Chapter 5

Greedy algorithms

A game like chess can be won only by thinking ahead : a player who is focused entirely on immediate advantage is easy to defeat. But in many other games, such as Scrabble, it is possible to do quite well by simply making whichever move seems best at the moment and not worrying too much about future consequences. This sort of myopic behavior is easy and convenient, making it an attractive algorithmic strategy. Greedy algorithms build up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Although such an approach can be disastrous for some computational tasks, there are many for which it is optimal. Our first example is that of minimum spanning trees.

5.1 Minimum spanning trees

Suppose you are asked to network a collection of computers by linking selected pairs of them. This translates into a graph problem in which nodes are computers, undirected edges are potential links, and the goal is to pick enough of these edges that the nodes are connected. But this is not all; each link also has a maintenance cost, reflected in that edge’s weight. What is the cheapest possible network?

A

B

C

D

E

F

4

1

4

(^3 4 2 )

6

4

One immediate observation is that the optimal set of edges cannot contain a cycle, because removing an edge from this cycle would reduce the cost without compromising connectivity:

Property 1 Removing a cycle edge cannot disconnect a graph.

So the solution must be connected and acyclic: undirected graphs of this kind are called trees. The particular tree we want is the one with minimum total weight, known as the minimum spanning tree. Here is its formal definition.

139

140 Algorithms

Input: An undirected graph G = (V, E); edge weights we. Output: A tree T = (V, E′), with E′^ ⊆ E, that minimizes

weight(T ) =

e∈E′

we.

In the preceding example, the minimum spanning tree has a cost of 16:

A

B

C

D

E

F

1

4

2 5

4

However, this is not the only optimal solution. Can you spot another?

5.1.1 A greedy approach

Kruskal’s minimum spanning tree algorithm starts with the empty graph and then selects edges from E according to the following rule.

Repeatedly add the next lightest edge that doesn’t produce a cycle.

In other words, it constructs the tree edge by edge and, apart from taking care to avoid cycles, simply picks whichever edge is cheapest at the moment. This is a greedy algorithm: every decision it makes is the one with the most obvious immediate advantage. Figure 5.1 shows an example. We start with an empty graph and then attempt to add edges in increasing order of weight (ties are broken arbitrarily):

B − C, C − D, B − D, C − F, D − F, E − F, A − D, A − B, C − E, A − C.

The first two succeed, but the third, B − D, would produce a cycle if added. So we ignore it and move along. The final result is a tree with cost 14, the minimum possible.

The correctness of Kruskal’s method follows from a certain cut property , which is general enough to also justify a whole slew of other minimum spanning tree algorithms.

Figure 5.1 The minimum spanning tree found by Kruskal’s algorithm.

B

A (^6 )

3

2 D 4 F

C E

5 4 1 2 4

B

A

D^ F

C E

142 Algorithms

Figure 5.2 T ∪ {e}. The addition of e (dotted) to T (solid lines) produces a cycle. This cycle must contain at least one other edge, shown here as e′, across the cut (S, V − S).





 

 

^  



      

e

S V − S

e′

5.1.2 The cut property

Say that in the process of building a minimum spanning tree (MST), we have already chosen some edges and are so far on the right track. Which edge should we add next? The following lemma gives us a lot of flexibility in our choice.

Cut property Suppose edges X are part of a minimum spanning tree of G = (V, E). Pick any subset of nodes S for which X does not cross between S and V − S , and let e be the lightest edge across this partition. Then X ∪ {e} is part of some MST.

A cut is any partition of the vertices into two groups, S and V − S. What this property says is that it is always safe to add the lightest edge across any cut (that is, between a vertex in S and one in V − S), provided X has no edges across the cut. Let’s see why this holds. Edges X are part of some MST T ; if the new edge e also happens to be part of T , then there is nothing to prove. So assume e is not in T. We will construct a different MST T ′^ containing X ∪ {e} by altering T slightly, changing just one of its edges. Add edge e to T. Since T is connected, it already has a path between the endpoints of e, so adding e creates a cycle. This cycle must also have some other edge e′^ across the cut (S, V − S) (Figure 8.3). If we now remove this edge, we are left with T ′^ = T ∪ {e} − {e′}, which we will show to be a tree. T ′^ is connected by Property 1, since e′^ is a cycle edge. And it has the same number of edges as T ; so by Properties 2 and 3, it is also a tree. Moreover, T ′^ is a minimum spanning tree. Compare its weight to that of T :

weight(T ′) = weight(T ) + w(e) − w(e′).

Both e and e′^ cross between S and V − S, and e is specifically the lightest edge of this type. Therefore w(e) ≤ w(e′), and weight(T ′) ≤ weight(T ). Since T is an MST, it must be the case that weight(T ′) = weight(T ) and that T ′^ is also an MST.

Figure 5.3 shows an example of the cut property. Which edge is e′?

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 143

Figure 5.3 The cut property at work. (a) An undirected graph. (b) Set X has three edges, and is part of the MST T on the right. (c) If S = {A, B, C, D}, then one of the minimum-weight edges across the cut (S, V − S) is e = {D, E}. X ∪ {e} is part of MST T ′, shown on the right.

(a) (^) A

B

C E

D F

(^2 2 )

3

1 4

1

2 1

(b)

Edges X:

A

B

C E

D F

MST T :

A

B

C E

D F

(c)

The cut:

A

B

C E

D^ F

e

S V^ −^ S

MST T ′:

A

B

C E

D^ F

5.1.3 Kruskal’s algorithm

We are ready to justify Kruskal’s algorithm. At any given moment, the edges it has already chosen form a partial solution, a collection of connected components each of which has a tree structure. The next edge e to be added connects two of these components; call them T 1 and T 2. Since e is the lightest edge that doesn’t produce a cycle, it is certain to be the lightest edge between T 1 and V − T 1 and therefore satisfies the cut property. Now we fill in some implementation details. At each stage, the algorithm chooses an edge to add to its current partial solution. To do so, it needs to test each candidate edge u − v to see whether the endpoints u and v lie in different components; otherwise the edge produces a cycle. And once an edge is chosen, the corresponding components need to be merged. What kind of data structure supports such operations? We will model the algorithm’s state as a collection of disjoint sets , each of which contains the nodes of a particular component. Initially each node is in a component by itself:

makeset(x): create a singleton set containing just x.

We repeatedly test pairs of nodes to see if they belong to the same set.

find(x): to which set does x belong?

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 145

In addition to a parent pointer π, each node also has a rank that, for the time being, should be interpreted as the height of the subtree hanging from that node.

procedure makeset(x) π(x) = x rank(x) = 0

function find(x) while x 6 = π(x) : x = π(x) return x

As can be expected, makeset is a constant-time operation. On the other hand, find follows parent pointers to the root of the tree and therefore takes time proportional to the height of the tree. The tree actually gets built via the third operation, union, and so we must make sure that this procedure keeps trees shallow. Merging two sets is easy: make the root of one point to the root of the other. But we have a choice here. If the representatives (roots) of the sets are rx and ry , do we make rx point to ry or the other way around? Since tree height is the main impediment to computational efficiency, a good strategy is to make the root of the shorter tree point to the root of the taller tree. This way, the overall height increases only if the two trees being merged are equally tall. Instead of explicitly computing heights of trees, we will use the rank numbers of their root nodes—which is why this scheme is called union by rank.

procedure union(x, y) rx = find(x) ry = find(y) if rx = ry: return if rank(rx) > rank(ry ): π(ry ) = rx else: π(rx) = ry if rank(rx) = rank(ry ) : rank(ry ) = rank(ry ) + 1

See Figure 5.6 for an example.

By design, the rank of a node is exactly the height of the subtree rooted at that node. This means, for instance, that as you move up a path toward a root node, the rank values along the way are strictly increasing.

Property 1 For any x , rank(x) < rank(π(x)).

A root node with rank k is created by the merger of two trees with roots of rank k − 1. It follows by induction (try it!) that

Property 2 Any root node of rank k has at least 2 k nodes in its tree.

146 Algorithms

This extends to internal (nonroot) nodes as well: a node of rank k has at least 2 k^ de- scendants. After all, any internal node was once a root, and neither its rank nor its set of descendants has changed since then. Moreover, different rank-k nodes cannot have common descendants, since by Property 1 any element has at most one ancestor of rank k. Which means

Property 3 If there are n elements overall, there can be at most n/ 2 k nodes of rank k.

This last observation implies, crucially, that the maximum rank is log n. Therefore, all the trees have height ≤ log n, and this is an upper bound on the running time of find and union.

Figure 5.6 A sequence of disjoint-set operations. Superscripts denote rank.

After makeset(A), makeset(B),... , makeset(G):

A^0 B^0 C^0 D^0 E^0 F^0 G^0

After union(A, D), union(B, E), union(C, F ):

A^0 B^0 C^0

D^1 E^1 F^1 G^0

After union(C, G), union(E, A):

B

1

F^1

C G^0 0

E

D^2

A^0

After union(B, G):

A

G^0

E^1 F 0

C^0

D^2

B^0

1

148 Algorithms

Figure 5.7 The effect of path compression: find(I) followed by find(K).

B^0

D^0

I^0 J^0 K^0

H^0

C^1

(^1) G 1

A^3

F

E^2

B^0

D^0

K^0

J^0

I^0

H^0

C^1 F^1

G^1

A^3

E^2

−→ B^0

D (^) H^0 J 0

C^1 E^2 F^1 I^0 K^0 G^1

A

0

3

to n to bring it down to 1 (or below 1 ). For instance, log∗^ 1000 = 4 since log log log log 1000 ≤ 1. In practice there will just be the first five of the intervals shown; more are needed only if n ≥ 265536 , in other words never. In a sequence of find operations, some may take longer than others. We’ll bound the overall running time using some creative accounting. Specifically, we will give each node a certain amount of pocket money, such that the total money doled out is at most n log∗^ n dollars. We will then show that each find takes O(log∗^ n) steps, plus some additional amount of time that can be “paid for” using the pocket money of the nodes involved—one dollar per unit of time. Thus the overall time for m find’s is O(m log∗^ n) plus at most O(n log∗^ n). In more detail, a node receives its allowance as soon as it ceases to be a root, at which point its rank is fixed. If this rank lies in the interval {k + 1,... , 2 k^ }, the node receives 2 k^ dollars. By Property 3, the number of nodes with rank > k is bounded by

n 2 k+^

n 2 k+^

n 2 k^

Therefore the total money given to nodes in this particular interval is at most n dollars, and since there are log∗^ n intervals, the total money disbursed to all nodes is ≤ n log∗^ n.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 149

Now, the time taken by a specific find is simply the number of pointers followed. Consider the ascending rank values along this chain of nodes up to the root. Nodes x on the chain fall into two categories: either the rank of π(x) is in a higher interval than the rank of x, or else it lies in the same interval. There are at most log∗^ n nodes of the first type (do you see why?), so the work done on them takes O(log∗^ n) time. The remaining nodes—whose parents’ ranks are in the same interval as theirs—have to pay a dollar out of their pocket money for their processing time. This only works if the initial allowance of each node x is enough to cover all of its payments in the sequence of find operations. Here’s the crucial observation: each time x pays a dollar, its parent changes to one of higher rank. Therefore, if x’s rank lies in the interval {k + 1 ,... , 2 k^ }, it has to pay at most 2 k^ dollars before its parent’s rank is in a higher interval; whereupon it never has to pay again.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 151

Figure 5.8 Prim’s algorithm: the edges X form a tree, and S consists of its vertices.





 

 

^  



 





     !!

" "

" "

$% $%

e

S V − S

X

growing to include the vertex v 6 ∈ S of smallest cost:

cost(v) = min u∈S w(u, v).

This is strongly reminiscent of Dijkstra’s algorithm, and in fact the pseudocode (Figure 5.9) is almost identical. The only difference is in the key values by which the priority queue is ordered. In Prim’s algorithm, the value of a node is the weight of the lightest incoming edge from set S, whereas in Dijkstra’s it is the length of an entire path to that node from the starting point. Nonetheless, the two algorithms are similar enough that they have the same running time, which depends on the particular priority queue implementation. Figure 5.9 shows Prim’s algorithm at work, on a small six-node graph. Notice how the final MST is completely specified by the prev array.

152 Algorithms

Figure 5.9 Top: Prim’s minimum spanning tree algorithm. Below: An illustration of Prim’s algorithm, starting at node A. Also shown are a table of cost/prev values, and the final MST.

procedure prim(G, w) Input: A connected undirected graph G = (V, E) with edge weights we Output: A minimum spanning tree defined by the array prev

for all u ∈ V : cost(u) = ∞ prev(u) = nil Pick any initial node u 0 cost(u 0 ) = 0

H = makequeue (V ) (priority queue, using cost-values as keys) while H is not empty: v = deletemin(H) for each {v, z} ∈ E: if cost(z) > w(v, z): cost(z) = w(v, z) prev(z) = v decreasekey(H, z)

B

A

(^6 )

3

2 D 4 F

C E

5 1 2 4 4

B

A

D F

C E

Set S A B C D E F {} 0 /nil ∞/nil ∞/nil ∞/nil ∞/nil ∞/nil A 5 /A 6 /A 4 /A ∞/nil ∞/nil A, D 2 /D 2 /D ∞/nil 4 /D A, D, B 1 /B ∞/nil 4 /D A, D, B, C 5 /C 3 /C A, D, B, C, F 4 /F

154 Algorithms

Figure 5.10 A prefix-free encoding. Frequencies are shown in square brackets.

Symbol Codeword A 0 B 100 C 101 D 11

0

A [70]

1

[60]

B [3] C [20]

D [37]

[23]

for our toy example, where (under the codes of Figure 5.10) the total size of the binary string drops to 213 megabits, a 17% improvement.

In general, how do we find the optimal coding tree, given the frequencies f 1 , f 2 ,... , fn of n symbols? To make the problem precise, we want a tree whose leaves each correspond to a symbol and which minimizes the overall length of the encoding,

cost of tree =

∑^ n

i=

fi · (depth of ith symbol in tree)

(the number of bits required for a symbol is exactly its depth in the tree). There is another way to write this cost function that is very helpful. Although we are only given frequencies for the leaves, we can define the frequency of any internal node to be the sum of the frequencies of its descendant leaves; this is, after all, the number of times the internal node is visited during encoding or decoding. During the encoding process, each time we move down the tree, one bit gets output for every nonroot node through which we pass. So the total cost—the total number of bits which are output—can also be expressed thus:

The cost of a tree is the sum of the frequencies of all leaves and internal nodes, except the root. The first formulation of the cost function tells us that the two symbols with the smallest frequencies must be at the bottom of the optimal tree , as children of the lowest internal node (this internal node has two children since the tree is full ). Otherwise, swapping these two symbols with whatever is lowest in the tree would improve the encoding. This suggests that we start constructing the tree greedily : find the two symbols with the smallest frequencies, say i and j, and make them children of a new node, which then has frequency fi + fj. To keep the notation simple, let’s just assume these are f 1 and f 2. By the second formulation of the cost function, any tree in which f 1 and f 2 are sibling-leaves has cost f 1 + f 2 plus the cost for a tree with n − 1 leaves of frequencies (f 1 + f 2 ), f 3 , f 4 ,... , fn:

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 155

f 1 f 2

f 5 f 4 f 3

f 1 + f 2

The latter problem is just a smaller version of the one we started with. So we pull f 1 and f 2 off the list of frequencies, insert (f 1 + f 2 ), and loop. The resulting algorithm can be described in terms of priority queue operations (as defined on page 120) and takes O(n log n) time if a binary heap (Section 4.5.2) is used.

procedure Huffman(f ) Input: An array f [1 · · · n] of frequencies Output: An encoding tree with n leaves

let H be a priority queue of integers, ordered by f for i = 1 to n: insert(H, i) for k = n + 1 to 2 n − 1 : i = deletemin(H), j = deletemin(H) create a node numbered k with children i, j f [k] = f [i] + f [j] insert(H, k)

Returning to our toy example: can you tell if the tree of Figure 5.10 is optimal?

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 157

5.3 Horn formulas

In order to display human-level intelligence, a computer must be able to perform at least some modicum of logical reasoning. Horn formulas are a particular framework for doing this, for expressing logical facts and deriving conclusions. The most primitive object in a Horn formula is a Boolean variable , taking value either true or false. For instance, variables x, y, and z might denote the following possibilities.

x ≡ the murder took place in the kitchen y ≡ the butler is innocent z ≡ the colonel was asleep at 8 pm

A literal is either a variable x or its negation x (“NOT x”). In Horn formulas, knowledge about variables is represented by two kinds of clauses :

  1. Implications , whose left-hand side is an AND of any number of positive literals and whose right-hand side is a single positive literal. These express statements of the form “if the conditions on the left hold, then the one on the right must also be true.” For instance,

(z ∧ w) ⇒ u

might mean “if the colonel was asleep at 8 pm and the murder took place at 8 pm then the colonel is innocent.” A degenerate type of implication is the singleton “⇒ x,” meaning simply that x is true: “the murder definitely occurred in the kitchen.”

  1. Pure negative clauses , consisting of an OR of any number of negative literals, as in

(u ∨ v ∨ y)

(“they can’t all be innocent”).

Given a set of clauses of these two types, the goal is to determine whether there is a consis- tent explanation: an assignment of true/false values to the variables that satisfies all the clauses. This is also called a satisfying assignment. The two kinds of clauses pull us in different directions. The implications tell us to set some of the variables to true, while the negative clauses encourage us to make them false. Our strategy for solving a Horn formula is this: We start with all variables false. We then proceed to set some of them to true, one by one, but very reluctantly, and only if we absolutely have to because an implication would otherwise be violated. Once we are done with this phase and all implications are satisfied, only then do we turn to the negative clauses and make sure they are all satisfied. In other words, our algorithm for Horn clauses is the following greedy scheme ( stingy is perhaps more descriptive):

Input: a Horn formula Output: a satisfying assignment, if one exists

158 Algorithms

set all variables to false

while there is an implication that is not satisfied: set the right-hand variable of the implication to true

if all pure negative clauses are satisfied: return the assignment else: return ‘‘formula is not satisfiable’’ For instance, suppose the formula is

(w ∧ y ∧ z) ⇒ x, (x ∧ z) ⇒ w, x ⇒ y, ⇒ x, (x ∧ y) ⇒ w, (w ∨ x ∨ y), (z).

We start with everything false and then notice that x must be true on account of the sin- gleton implication ⇒ x. Then we see that y must also be true, because of x ⇒ y. And so on. To see why the algorithm is correct, notice that if it returns an assignment, this assign- ment satisfies both the implications and the negative clauses, and so it is indeed a satisfying truth assignment of the input Horn formula. So we only have to convince ourselves that if the algorithm finds no satisfying assignment, then there really is none. This is so because our “stingy” rule maintains the following invariant:

If a certain set of variables is set to true, then they must be true in any satisfying assignment.

Hence, if the truth assignment found after the while loop does not satisfy the negative clauses, there can be no satisfying truth assignment.

Horn formulas lie at the heart of Prolog (“programming by logic”), a language in which you program by specifying desired properties of the output, using simple logical expressions. The workhorse of Prolog interpreters is our greedy satisfiability algorithm. Conveniently, it can be implemented in time linear in the length of the formula; do you see how (Exercise 5.32)?

5.4 Set cover

The dots in Figure 5.11 represent a collection of towns. This county is in its early stages of planning and is deciding where to put schools. There are only two constraints: each school should be in a town, and no one should have to travel more than 30 miles to reach one of them. What is the minimum number of schools needed? This is a typical set cover problem. For each town x, let Sx be the set of towns within 30 miles of it. A school at x will essentially “cover” these other towns. The question is then, how many sets Sx must be picked in order to cover all the towns in the county?

SET COVER Input: A set of elements B; sets S 1 ,... , Sm ⊆ B