









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!










Chapter 7
Greedy Algorithms
An optimization problem is one in which you want to find, not just a solution, but the best solution. Search techniques look at many possible solutions. E.g. dynamic programming or backtrack search. A “ greedy algorithm” sometimes works well for optimization problems
A greedy algorithm works in phases. At each phase:
For some problems, greedy approach always gets optimum. For others, greedy finds good, but not always best. If so, it is called a greedy heuristic, or approximation. For still others, greedy approach can do very poorly.
Suppose you want to count out a certain amount of money, using the fewest possible bills (notes) and coins. A greedy algorithm to do this would be: at each step, take the largest possible note or coin that does not overshoot.
while (N > 0){ give largest denomination coin ≤ N reduce N by value of that coin }
Consider the currency in U.S.A. There are paper notes for one dollar, five dollars, ten dollars, twenty dollars, fifty dollars and hundred dollars. The notes are also called “bills”. The coins are one cent, five cents (called a “nickle”), ten cents (called a “dime”) and twenty five cents (a “quarter”). In Pakistan, the currency notes are five rupees, ten rupees, fifty rupees, hundred rupees, five hundred rupees and thousand
To pay (j − di) units it takes C[i, j − di] coins. Thus,
C[i, j] = 1 + C[i, j − di]
Since we want to minimize the number of coins used,
C[i, j] = min(C[i − 1, j], 1 + C[i, j − di])
Here is the dynamic programming based algorithm for the coin change problem.
1 d[1..n] = {1, 4, 6} // (coinage, for example) 2 for i = 1 to k 3 do c[i, 0] ← 0 4 for i = 1 to k 5 do for j = 1 to N 6 do if (i = 1 & j < d[i]) 7 then c[i, j] ← ∞ 8 else if (i = 1 ) 9 then c[i, j] ← 1 + c[1, j − d[ 1 ]] 10 else if (j < d[i]) 11 then c[i, j] ← c[i − 1, j] 12 else c[i, j] ← min (c[i − 1, j], 1 + c[i, j − d[i]]) 13 return c[k, N]
Greedy algorithm (non-optimal) takes O(k) time. Dynamic Programming takes O(kN) time. Note that N can be as large as 2 k^ so the dynamic programming algorithm is really exponential in k.
The Huffman codes provide a method of encoding data efficiently. Normally, when characters are coded using standard codes like ASCII. Each character is represented by a fixed-length codeword of bits, e.g., 8 bits per character. Fixed-length codes are popular because it is very easy to break up a string into its individual characters, and to access individual characters and substrings by direct indexing. However, fixed-length codes may not be he most efficient from the perspective of minimizing the total quantity of data.
Consider the string “ abacdaacac”. if the string is coded with ASCII codes, the message length would be 10 × 8 = 80 bits. We will see shortly that the same string encoded with a variable length Huffman encoding scheme will produce a shorter message.
Here is how the Huffman encoding algorithm works. Given a message string, determine the frequency of occurrence (relative probability) of each character in the message. This can be done by parsing the message and counting how many time each character (or symbol) appears. The probability is the number of occurrence of a character divided by the total characters in the message. The frequencies and probabilities for the example string “ abacdaacac” are
character a b c d frequency 5 1 3 1 probability 0.5 0.1 0.3 0.
Next, create binary tree (leaf) node for each symbol (character) that occurs with nonzero frequency Set node weight equal to the frequency of the symbol. Now comes the greedy part: Find two nodes with smallest frequency. Create a new node with these two nodes as children, and with weight equal to the sum of the weights of the two children. Continue until we have a single tree.
Finding two nodes with the smallest frequency can be done efficiently by placing the nodes in a heap-based priority queue. The min-heap is maintained using the frequencies. When a new node is created by combining two nodes, the new node is placed in the priority queue. Here is the Huffman tree building algorithm.
HUFFMAN(N, symbol[1..N], freq[1..N]) 1 for i = 1 to N 2 do t ← TreeNode(symbol[i], freq[i]) 3 pq.insert(t, freq[i]) // priority queue 4 for i = 1 to N − 1 5 do x = pq.remove(); y = pq.remove() 6 z ← new TreeNode 7 z.left ← x; z.right ← y 8 z.freq ← x.freq + y.freq 9 pq.insert(z, z.freq); 10 return pq.remove(); // root
Figure 7.1 shows the tree built for the example message “abacdaacac”
Huffman algorithm uses a greedy approach to generate a prefix code T that minimizes the expected length B(T ) of the encoded string. In other words, Huffman algorithm generates an optimum prefix code. The question that remains is that why is the algorithm correct?
Recall that the cost of any encoding tree T is
B(T ) = n
x∈C
p(x)dT(x)
Our approach to prove the correctness of Huffman Encoding will be to show that any tree that differs from the one constructed by Huffman algorithm can be converted into one that is equal to Huffman’s tree without increasing its costs. Note that the binary tree constructed by Huffman algorithm is a full binary tree.
Claim:
Consider two characters x and y with the smallest probabilities. Then there is optimal code tree in which these two characters are siblings at the maximum depth in the tree.
Proof:
Let T be any optimal prefix code tree with two siblings b and c at the maximum depth of the tree. Such a tree is shown in Figure 7.2Assume without loss of generality that
p(b) ≤ p(c) and p(x) ≤ p(y)
Figure 7.2: Optimal prefix code tree T
Since x and y have the two smallest probabilities (we claimed this), it follows that
p(x) ≤ p(b) and p(y) ≤ p(c)
Since b and c are at the deepest level of the tree, we know that
d(b) ≥ d(x) and d(c) ≥ d(y) (d is the depth)
Thus we have
p(b) − p(x) ≥ 0
and
d(b) − d(x) ≥ 0
Hence their product is non-negative. That is,
(p(b) − p(x)) · (d(b) − d(x)) ≥ 0
Now swap the positions of x and b in the tree
T
Figure 7.3: Swap x and b in tree prefix tree T
This results in a new tree T ′
smallest probabilities. Then there is optimal code tree in which these two characters are siblings at the maximum depth in the tree.
The claim we just proved asserts that the first step of Huffman algorithm is the proper one to perform (the greedy step). The complete proof of correctness for Huffman algorithm follows by induction on n.
Claim: Huffman algorithm produces the optimal prefix code tree.
Proof: The proof is by induction on n, the number of characters. For the basis case, n = 1 , the tree consists of a single leaf node, which is obviously optimal. We want to show it is true with exactly n characters.
Suppose we have exactly n characters. The previous claim states that two characters x and y with the lowest probability will be siblings at the lowest level of the tree. Remove x and y and replace them with a new character z whose probability is p(z) = p(x) + p(y). Thus n − 1 characters remain.
Consider any prefix code tree T made with this new set of n − 1 characters. We can convert T into prefix code tree T ′^ for the original set of n characters by replacing z with nodes x and y. This is essentially undoing the operation where x and y were removed an replaced by z. The cost of the new tree T ′^ is
B(T ′) = B(T ) − p(z)d(z) + p(x)[d(z) + 1 ] + p(y)[d(z) + 1 ] = B(T ) − (p(x) + p(y))d(z) + (p(x) + p(y))[d(z) + 1 ] = B(T ) + (p(x) + p(y))[d(z) + 1 − d(z)] = B(T ) + p(x) + p(y)
The cost changes but the change depends in no way on the structure of the tree T (T is for n − 1 characters). Therefore, to minimize the cost of the final tree T ′, we need to build the tree T on n − 1 characters optimally. By induction, this is exactly what Huffman algorithm does. Thus the final tree is optimal.
The activity scheduling is a simple scheduling problem for which the greedy algorithm approach provides an optimal solution. We are given a set S = {a 1 , a 2 ,... , an} of n activities that are to be scheduled to use some resource. Each activity ai must be started at a given start time si and ends at a given finish time fi.
An example is that a number of lectures are to be given in a single lecture hall. The start and end times have be set up in advance. The lectures are to be scheduled. There is only one resource (e.g., lecture hall) Some start and finish times may overlap. Therefore, not all requests can be honored. We say that two activities ai and aj are non-interfering if their start-finish intervals do not overlap. I.e, (si, fi) ∩ (sj, fj) = ∅. The activity selection problem is to select a maximum-size set of mutually non-interfering activities for use of the resource.
So how do we schedule the largest number of activities on the resource? Intuitively, we do not like long
activities Because they occupy the resource and keep us from honoring other requests. This suggests the greedy strategy: Repeatedly select the activity with the smallest duration (fi − si) and schedule it, provided that it does not interfere with any previously scheduled activities. Unfortunately, this turns out to be non-optimal
Here is a simple greedy algorithm that works: Sort the activities by their finish times. Select the activity that finishes first and schedule it. Then, among all activities that do not interfere with this first job, schedule the one that finishes first, and so on.
SCHEDULE(a[1..N]) 1 sort a[1..N] by finish times 2 A ← {a[ 1 ]}; // schedule activity 1 first 3 prev ← 1 ; // most recently scheduled 4 for i = 2 to N 5 do if (a[i].start ≥ a[prev].finish) 6 then A ← A ∪ a[i]; prev ← i
Figure 7.5 shows an example of the activity scheduling algorithm. There are eight activities to be scheduled. Each is represented by a rectangle. The width of a rectangle indicates the duration of an activity. The eight activities are sorted by their finish times. The eight rectangles are arranged to show the sorted order. Activity a 1 is scheduled first. Activities a 2 and a 3 interfere with a 1 so they ar not selected. The next to be selected is a 4. Activities a 5 and a 6 interfere with a 4 so are not chosen. The last one to be chosen is a 7. Eventually, only three out of the eight are scheduled.
Timing analysis: Time is dominated by sorting of the activities by finish times. Thus the complexity is O(N log N).
X a (^) 2 a (^) 3 a (^) 4 a (^) 5 a (^) 6 a (^7) a (^8)
a (^) 1 a (^) 2 a (^) 3 a (^) 4 a (^) 5 a (^) 6 a (^7) a (^8)
Figure 7.6: Activity X = a 1
We claim that A′^ = A − {x} ∪ {a 1 } is a feasible schedule, i.e., it has no interfering activities. This because A − {x} cannot have any other activities that start before x finishes, since otherwise, these activities will interfere with x.
X a (^) 3 a (^) 4 a (^) 5 a (^) 6 a (^7) a (^8)
a 1
a (^) 3 a (^) 4 a (^) 5 a (^) 6 a (^7) a (^8)
X
Figure 7.7: New schedule A′^ by replacing x with ctivity a 1.
Since a 1 is by definition the first activity to finish, it has an earlier finish time than x. Thus a 1 cannot interfere with any of the activities in A − {x}. Thus, A′^ is a feasible schedule. Clearly A and A′^ contain the same number of activities implying that A′^ is also optimal.
Claim:
The greedy algorithm gives an optimal solution to the activity scheduling problem.
Proof:
The proof is by induction on the number of activities. For the basis case, if there are no activities, then the greedy algorithm is trivially optimal. For the induction step, let us assume that the greedy algorithm is optimal on any set of activities of size strictly smaller than |S| and we prove the result for S. Let S′^ be the set of activities that do not interfere with activity a 1 , That is
S′^ = {ai ∈ S|si ≥ f 1 }
Any solution for S′^ can be made into a solution for S by simply adding activity a 1 , and vice versa. Activity a 1 is in the optimal schedule (by the above previous claim). It follows that to produce an optimal schedule for the overall problem, we should first schedule a 1 and then append the optimal schedule for S′. But by induction (since |S′| < |S|), this exactly what the greedy algorithm does.
Earlier we saw the 0-1 knapsack problem. A knapsack can only carry W total weight. There are n items; the ith^ item is worth vi and weighs wi. Items can either be put in the knapsack or not. The goal was to maximize the value of items without exceeding the total weight limit of W. In contrast, in the fractional knapsack problem, the setup is exactly the same. But, one is allowed to take fraction of an item for a fraction of the weight and fraction of value. The 0-1 knapsack problem is hard to solve. However, there is a simple and efficient greedy algorithm for the fractional knapsack problem.
Let ρi = vi/wi denote the value per unit weight ratio for item i. Sort the items in decreasing order of ρi. Add items in decreasing order of ρi. If the item fits, we take it all. At some point there is an item that does not fit in the remaining space. We take as much of this item as possible thus filling the knapsack completely.
5 10
20
30
40
knapsack $ 6 2 5 3 4
$20 $100 $90 $
60
Greedy solution to 0-1 knapsack
5
20
30 $
$
$
$
Figure 7.9: Greedy solution for the 0-1 knapsack problem (non-optimal)
5
10
20
30
40
knapsack $ 6 2 5 3 4
$20 $100 $90 $
60
Optimal solution to 0-1 knapsack
20
40
$
$
$
Figure 7.10: Optimal solution for the 0-1 knapsack problem