Greedy Algorithms
Chapter 16
CPTR 430 Algorithms Greedy Algorithms
Greedy Algorithms Chapter 16 1 CPTR 430 Algorithms Greedy - - PowerPoint PPT Presentation
Greedy Algorithms Chapter 16 1 CPTR 430 Algorithms Greedy Algorithms Greedy Algorithms For some optimization problems, dynamic programming algorithms are overkill A greedy algorithm always makes a choice that looks best at the moment
CPTR 430 Algorithms Greedy Algorithms
■ For some optimization problems, dynamic programming algorithms are
■ A greedy algorithm always makes a choice that looks best at the
■ The strategy: A locally optimal choice will ultimately lead to a globally
■ Greedy algorithms do not always yield optimal solutions ■ For some kinds of problems, though, greedy algorithms always yield
❚ Dijkstra’s shortest path in a graph ❚ Prim’s minimum spanning tree of a graph ❚ Plus many others . . .
CPTR 430 Algorithms Greedy Algorithms
■ Need to schedule several activities that compete for a common
■ Each activity ai has a start time si and a finish time fi, where
■ Activity ai takes place during the half-open interval
✂■ Activities ai and a j are compatible if the intervals
✂CPTR 430 Algorithms Greedy Algorithms
■ Select a maximum size subset of mutually compatible activities ■ Example:
■ The subset
■ The subsets
CPTR 430 Algorithms Greedy Algorithms
■ Find the optimal substructure ■ Define set Si j:
■ Si j is the set of all activities that are compatible with both ai and a j ■ To make a nice, regular algorithm, create dummy activities a0 and an
✂1
1
■ S, the set of all activities, can thus be written S0
✄n
✂1, ■ 0
CPTR 430 Algorithms Greedy Algorithms
■ Sort the activities in monotonically increasing order of finish time:
1 ■ i
✂❚ Prove by contradiction ❚ Suppose ak
✆❚ This means fi
■ Thus, for subproblems we chose a maximal-size subset of mutually
CPTR 430 Algorithms Greedy Algorithms
■ Let a solution to Si j contain activity ak ■ fi
■ Use ak to split the problem into two subproblems: ❚ Sik, the set of activities that start after ai finishes and before ak starts ❚ Sk j, the set of activities that start after ak finishes and before a j starts ❚ Let the optimal solution to Spq be expressed as Apq
❚ The solution for Si j, Ai j, is then Aik
✁CPTR 430 Algorithms Greedy Algorithms
■ ak
✆■ To show, suppose otherwise ■ Let
✁■ Let
✁CPTR 430 Algorithms Greedy Algorithms
■ Choose an activity, ak, that is a member of Ai j, an optimal solution ■ Find the optimal solutions to Sik and Sk j (that is, Aik and Ak j) ■ Combine the results:
■ To solve the entire problem, S0
✄n
✂1, find A0
✄n
✂1
CPTR 430 Algorithms Greedy Algorithms
■ Let c
✂■ Si j
■ c
✂❚ i
☎❚ Check all these possible values for k (all j
✁❚ c
✂i
✂k
✂j
CPTR 430 Algorithms Greedy Algorithms
■ Let Si j
✄■ fm
❚ The first item means that am is in a maximal-size subset of mutually
❚ The second item means that of the two subproblems formed by
CPTR 430 Algorithms Greedy Algorithms
■ Let Ai j be a maximal-size subset of mutually compatible activities in Si j ■ Order the elements of Ai j in monotonically increasing order of finish
■ Let ak be the first element in Ai j: ❚ ak
❚ If ak
✄❚ The activities in A
❙ The activities in Ai j are mutually compatible ❙ ak is the first activity to finish in Ai j ❙ fm
✁❚ Since
✁CPTR 430 Algorithms Greedy Algorithms
■ Suppose Sim
✄■ Sim
✄■ fk
✁Greedy Algorithms
■ DP solution
✄■ DP solution
✄■ Greedy solution
✄■ Greedy solution
✄CPTR 430 Algorithms Greedy Algorithms
■ DP is naturally bottom-up:
■ The greedy approach is naturally top-down:
CPTR 430 Algorithms Greedy Algorithms
■ In the Activity scheduling problem, we always choose the activity with
■ The choice is “greedy” since it leaves more activities left to be
■ This maximizes the amount of unscheduled time so that more activities
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
public class ActivitySelector { // . . . private static Time[] concat(Time[] array1, Time[] array2) { Time[] result = null; // Default value if ( array1 == null ) { result = array2; } else if ( array2 == null ) { result = array1; } else { result = new Time[array1.length + array2.length]; System.arraycopy(array1, 0, result, 0, array1.length); System.arraycopy(array2, 0, result, array1.length, array2.length); } return result; // . . . } }
CPTR 430 Algorithms Greedy Algorithms
public class ActivitySelector { // . . . private static Time[] recursiveActivitySelector(Time[] t, int i, int j) { int m = i + 1; // Search for an activity t[m] that is compatible with t[i] while ( m < j && t[m].start < t[i].finish ) { m++; } if ( m < j ) { // Add the activity, if one was found return concat(new Time[] { t[m] }, recursiveActivitySelector(t, m, j)); } else { // None was found return null; } } // . . . }
CPTR 430 Algorithms Greedy Algorithms
■ The method recursiveActivitySelector() assumes that the array
■ If it is not sorted, it can be sorted in O
■ The recursiveActivitySelector() method itself runs in time Θ
❚ Each activity is considered exactly once, in the while loop ❚ A recursive call never examines an activity that has already been
CPTR 430 Algorithms Greedy Algorithms
■ The method recursiveActivitySelector() uses tail recursion ❚ Tail recursive methods can be easily rewritten to use iteration instead
❚ Compilers/interpreters for some programming languages automatically
❚ Use a local variable to maintain the cumulative computation that the
❚ The iterative version is more efficient practically in terms of time and
CPTR 430 Algorithms Greedy Algorithms
public class ActivitySelector { // . . . private static Time[] greedyActivitySelector(Time[] t) { int n = t.length - 1; Time[] result = new Time[] { t[1] }; int i = 1; // Search for an activity t[m] that is compatible with t[i] for ( int m = 2; m <= n; m++ ) { if ( t[m].start >= t[i].finish ) { // t[m] compatible? result = concat(result, new Time[] { t[m] }); i = m; } } return result; } // . . . }
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ Greedy-choice property ■ Optimal substructure
CPTR 430 Algorithms Greedy Algorithms
■ Consider the best choice for the given problem without considering the
■ In DP
■ DP is therefore bottom-up ■ Greedy algorithms are top-down
CPTR 430 Algorithms Greedy Algorithms
■ Must prove that the greedy choice at each step yields a globally optimal
■ For the choice to be made efficiently, we often order the data in some
CPTR 430 Algorithms Greedy Algorithms
■ A problem exhibits optimal substructure if an optimal solution contains
■ To separate greedy algorithms from DP
❚ We must show that the greedy choice plus an optimal solution to that
❚ This requires an inductive proof, in one form or another
CPTR 430 Algorithms Greedy Algorithms
■ 0-1 knapsack problem ■ Fractional knapsack problem
CPTR 430 Algorithms Greedy Algorithms
■ n items ■ Each item is indivisble ■ Item i is worth vi dollars ■ Item i weighs wi kilograms ■ A knapsack (backpack) can hold W kilograms ■ Stuff the knapsack with as many items as possible to maximize the
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ 0-1: ❚ Consider the most valuable load that weighs at most W kilograms ❚ Remove item j from the knapsack ❚ The remaining load must be the most valuable load of items
■ Fractional: ❚ Consider the most valuable load that weighs at most W kilograms ❚ Remove w kilograms from one item j in the knapsack ❚ The remaining load must be the most valuable load (excluding w j
✁CPTR 430 Algorithms Greedy Algorithms
■ Compute the value per kilogram of each item, vi
■ Take as much as possible of the item with the greatest value-to-weight
■ If this item is exhausted and the knapsack can hold more, choose the
■ Continue this strategy until the knapsack can hold no more
CPTR 430 Algorithms Greedy Algorithms
50 Knapsack 30 Item 3 $120 20 Item 2 $100 10 Item 1 $60
CPTR 430 Algorithms Greedy Algorithms
10 20 30 20 $100 $60 $80 + + = $240 50 Knapsack 30 Item 3 $120 20 Item 2 $100 10 Item 1 $60 $6 $/kg 5 $/kg 4 $/kg
CPTR 430 Algorithms Greedy Algorithms
50 Knapsack 30 Item 3 $120 20 Item 2 $100 10 Item 1 $60
CPTR 430 Algorithms Greedy Algorithms
50 Knapsack 30 Item 3 $120 20 Item 2 $100 10 Item 1 $60 20 $100 $60 30 10 10 30 20 $100 $120 $120 $60 = $160 = $180 = $220 + + +
CPTR 430 Algorithms Greedy Algorithms
■ The empty space left over in the knapsack lowers the effective value
■ When considering the inclusion of an item we must consider the two
❚ the result when the item is added ❚ the result when the item is not added ■ There obviously will be multiple overlapping subproblems—as we saw
■ DP can be used to solve the 0-1 knapsack problem
CPTR 430 Algorithms Greedy Algorithms
■ Consider a data file consisting of 100,000 characters ■ The characters a, b, c, d, e, and f, in various quantities each, are
■ For example, the file might begin:
CPTR 430 Algorithms Greedy Algorithms
■ Use three bits to represent the six different characters:
■ 100,000 characters = 300,000 bits
CPTR 430 Algorithms Greedy Algorithms
■ The “standard” approach uses fixed-length encoding ■ Each character code uses the same number of bits ■ No delimiters needed; just grab the next three bits to get the next
CPTR 430 Algorithms Greedy Algorithms
■ more frequently appearing characters use fewer bits ■ less frequently occurring characters use more bits
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ Since the characters have variable bit lengths, do we now need
■ No code word must be the prefix of any other code word ■ Such codes are called prefix codes ■ The file
CPTR 430 Algorithms Greedy Algorithms
■ A binary tree can be used to conveniently represent prefix codes ■ Leave represent the characters ■ The bitstring encodes a path to a leaf
1 1 1 1 1 1 1 1 1 a :45 b:13 c:12 d:16 e:9 f :5 28 14 86 100 58 100 a:45 14 b :13 c:12 d:16 e:9 f:5 25 55 14 30
CPTR 430 Algorithms Greedy Algorithms
1 1 1 1 1 1 1 1 1 a:45 b :13 c:12 d:16 e:9 f:5 28 14 86 100 58 14 100 a :45 b:13 c :12 d:16 e :9 f:5 25 55 14 30
■ An optimal code for a file is
■ The fixed-length code is non-optimal ■ The given variable-length code may
CPTR 430 Algorithms Greedy Algorithms
■ C is the alphabet of characters ■ T has
■ T has
■ If c
✂■ If c
✂■ The number of bits required to encode a fi le given tree T is
c
✆C
■ B
✄CPTR 430 Algorithms Greedy Algorithms
■ David Huffman in 1952 devised an algorithm for that creates optimal
■ Each character is wrapped in an object with the character’s associated
■ The two objects with the lowest frequencies are merged into an internal
■ This process continues until only one object remains—the internal node
■
✁■ Huffman’s algorithm uses a min-priority queue to identify the two nodes
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ A HuffmanNode is an object that can be
❚ Subclass CharNode is an object that
❚ Subclass InteriorNode is an interior
■ C is a set (array) of HuffmanNodes ■ Q is a minheap of HuffmanNode objects
HuffmanNode CharNode InteriorNode
CPTR 430 Algorithms Greedy Algorithms
■ The creation of the minheap Q
int n = C.length; MinHeap Q = new MinHeap(n, C);
■ The for loop is executed n
✁for ( int i = 0; i < n - 1; i++ ) { HuffmanNode left = Q.extractMinimum(), right = Q.extractMinimum(); InteriorNode z = new InteriorNode(left.getFrequency() + right.getFrequency(), left, right); Q.insert(z); }
■ Thus, for n characters, huffman() takes O
✄CPTR 430 Algorithms Greedy Algorithms
■ the greedy-choice property ■ the optimal-substructure property
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ We must be able to take tree T which represents an arbitrary optimal
■ The code words for x and y will thus have the same length and differ
■ If we can do this, since the Huffman tree is built in a bottom-up manner
CPTR 430 Algorithms Greedy Algorithms
■ Let a and b be two characters that are sibling leaves of maximum depth
■ Without loss of generality, assume f
✂■ Transform T to produce T
■ Next, transform T
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
c
✁C
c
✁C
■ f
✂■ dT
CPTR 430 Algorithms Greedy Algorithms
■ Since T is optimal, B
■ B
■ Thus, T
CPTR 430 Algorithms Greedy Algorithms
■ Lemma 16.2 shows that we can begin building the Huffman tree by
■ This merger choice produces an internal node witht the lowest cost
CPTR 430 Algorithms Greedy Algorithms
CPTR 430 Algorithms Greedy Algorithms
■ For each c
✆■ Thus, f
✂■ dT
■ So,
CPTR 430 Algorithms Greedy Algorithms
Greedy Algorithms
■ Suppose T does not represent a optimal prefix code for C ■ Therefore, there exists tree T
■ Using the results of Lemma 16.2 and without loss of generality let x and
■ Let T
CPTR 430 Algorithms Greedy Algorithms
■ This contradicts the assumption that T
CPTR 430 Algorithms Greedy Algorithms