Greedy Algorithms
Coin Changing
Goal: Given U.S, Currency denominations , devise a method to pay amount to cusotmer using the fewest coins.
Cashier's Algorithm
Cashier's algorithm: at each itearation add coin of the largets value that does not take us past the amount to be paid:
Sort coin denominations so that S (multiset of coins selected).
While ,
-
largest coin denomination such that .
-
If (no such )
- Return "no solution"
-
Else
- .
Return
Cashier's Algorithm is not always optimal.
The properties of any optimal solutions (for U.S. coin denominations):
- the number of pennies (proof: replace 5 pennies with 1 nickel)
- number of nickels .
- number of quarters
- number of nickels + dimes (proof: nickel, replace 3 dimes and 0 nickels with 1 quarter and 1 nickel; replace 2 dimes and 1 nickel with 1 quarter)
The optimality of cashier's algorithm (for U.S. coin denominations):
theorem: cashieer's algoirthm is optimal for U.S. coins proof (by induction on amount to be paid )
- consider the optimal way to change : greedy takes coin .
- We claim that any optimal solution must take coin .
- if not, it needs enough coin of type to add up to .
- table below indicates no optimal solution can do this.
- Problem reduces to coin-changing cents, which, by induction, is optimally solved by cahsier's algorithm.
Interview Scheduling
Job starts at and finishes at . Two jobs are compatible if they don't overlap. Goal: find the maximum subset of mutually compatible jobs.
Earliest Finish Time First Algorithm
Earliest-finish-time-first ()
Sort jobs by finish tmes and renumber so that . S (set of jobs selected). For to
- If (job is compatible with )
Return .
Preposition: can implement earliest-finish-time first in time.
- keep track of job that was added last to .
- Job is compatible with iff
- Sorting by finish times takes time.
Theorem: the earliest-finish-time-first algorithm is optimal. Proof (by contradiction):
- assume greedy is not optimal, and let's see wha thappens
- Let denote the set of jobs selected by greedy.
- Let denote thes et of jobs in an optimal solution with for the largest possible value of .
Interval Partitioning
Lecture starts at and finishes at .
Goal: find minimum number of classrooms to schedule all lectures so that no two lectures occur at the same time in the same room.
Earliest-start-time-first ()
Sort lectures by start times and renumber so that (number of allocated classrooms)
For to ,
- If (leucture is compatible with some classroom)
- Schedule lecture in any such classroom .
- Else
- Allocate a new classroom .
- Schedule lecutre in classroom
- .
- Return schedule
Lower bound on optimal solution: the depth of a set of open intervals is the maximum number of intervals that contain any given point.
- the number of classrooms needed depth.
Q: does the minimum number of classrooms needed always equal depth? A: Yes! Moreover, earliest-start-time-first algorithm finds a schedule number of classroom equals the depth.
Analysis: the earliest-start-time-first algorithm never schedules two incompatible lectures in the same classroom.
- Theorem: earliest-start-time-first algorithm is optimal.
- Proof:
- let number of classrooms that the algorithm allocates.
- Classroom is opened because we needed to schedule a lecture, say , that is incompatible with a lecture in each of other classrooms.
- Thus, these lectures each end after .
- Since we sorted by start time, each of these incompatible lecture in each of these incompatible lectures start no later than .
- Thus, we have lectures overlapping at time .
- Key observation all schedules use classrooms.
Scheduling to minimize lateness.
Single resource processes one job at a time. Job requires units of processing time and is due at . If starts at time , it finishes at time . Lateness = . Goal: schedule all jobs to minimize maximum lateness .
Earliest-Deadline-First (): Sort jobs by due times and renumber so that . . For to :
- Assign job to interval []
- ; .
Return intervals
We want no idle time.
- Observation 1: there exists an optimal schedule with no idle time.
- Observation 2: the earliest-deadline-first schedule has no idle time.
Inversions: given a schedule , an inversion is a pair of jobs and such that: but is scheduled before .
Observation 3: the earliest-deadline-first schedule is the unique idle-free schedule with no inversions.
Observation 4: if an idle-free schedule has an inversion, then it has an adjacent inversion (two inverted jobs scheduled consecutively). The proof is as follows:
- let be a closeset inversion
- let be element immediately to the rght of .
- case 1: then is an adjacent inversion
- case 2: then is a closer inversion since .
Key claim: exchanging two adjacent, inverted jobs and reduces the number of inversions by 1 and does not increase the max lateness.
Proof: let be the lateness before the swal and let be it afterwards.
- for all
- If job is late, (by definition)
- ( now finishes at time )
- ()
- (by definition)
Analysis
Theorem: the earliest-deadline-first schedule is optimal. Proof by contradiction: Define to be an optimal schedule with the fewest inversion (optimal schedule can have inversions).
- Can assume has no idle time (by observaion 1)
- Case 1: [ has no inversions] then (by observation 3)
- Case 2: [ has an inversion]
- Let be an adjacent inversion (by observation 4)
- Exchanging jobs and decreases the number of inversions by 1 without increasing max lateness (key claim)
- contradicts "fewest inversions" part of the definition of .
Greedy Analysis Strategy
Greedy algorithm stays ahead. Show that after each step of the greedy algorithm, its solution is at least as good as any other algorithm's.
Structural: discover a simple "structural" bound asserting that every possible solution must have a certain value. Then show that your algoirthm always achieves this bound.
Exchange argument: gradually transofrm any solution to the one you found by the greedy algirhtm without hurting its quality.
The other greedy algorithms: gale-shapley, kruskal, prim, dijkstra, huffman,...
Dijkstra's Algorithm
The Problem
The Single-pair shortest path problem: Given a diagraph , edge lengths , source , and destination , find a shortest directed path from to .
The Single-source shortest path problem: Given a diagraph , edge lengths , source , and find a shortest directed path from to every node.
Dijkstra's Algorithm (for single-source shortest paths problem): The greedy approach: maintain a set of explored nodes for which algorithm has determined length of a shortest path.
- initialize , .
- repeatedly choose unexplored node which minimizes (the length of a shortest path from to some node in explored part , followed by a single edge ). add to , and set .
- To recover path, set that achieves min.
Proof of correctness:
Invariant: for each node = length of a shortest path. Proof by induction on :
- base case: is easy since and
- inductive hypothesis: assume true for
- let be the next node added to , and let be the final edge.
- a shortest path plus is an path of length .
- Consider any other path . We show that it is no shorter than .
- Let be the first edge in that leaves , and let be the subpath from to .
- The length is already as soon as it reaches .
- explanation for each sign:
- non-negative lengths
- induction hypothesis
- definition of
- dijkstra chose instead of .
Efficient Implementation
Critical optimization 1: for each unexplored node : explicitly maintain instead of computing directly from definition:
- For each can only decrease (because set increases).
- More specifically, suppose is added to and there is an edge leaving . Then, it suffices to update: (recall: for each , length of shortest path).
Critical optimization 2: use a min-oriented priority queue (PQ) to choose an unexplored node that minimizes .
Implementation:
- Algorithm maintains for each node .
- Priority queue stores unexplored nodes, using as priorities.
- Once is deleted from the PQ, length of a shortest path.
Dijkstra : For each , ; .
- Create an empty priority queue . For each : insert . While (is-not-empty()):
- del-min
- Foreach edge leaving :
- If ()
- Decrease-key ()
- ;
- If ()
Minimum Spanning Trees
A path is a sequence of edges which connects a sequence of nodes.
A cycle is a path with no repeated nodes or edges other than the starting and ending nodes.
Example Path
A cut is a partition of the nodes into two nonempty subsets and . The cutset of a cut is the set of edges with exactly one endpoint in .
Cycle-cut intersection proposition: a cycle and a cutset intersect in an even number of edges.
- A cycle and a cutset intersect in an even number of edges.
Let be a subgraph of an undirected graph . is a spanning tree of if is both acyclic and connected.
Some properties of spanning trees. Proposition: Let be a subgraph of an undirected graph . Then, the following are equivalent:
- is a spanning tree of G
- is acyclic and connected
- is connected and has edges
- is acyclic and has edges
- is minimally connected: removal of any edge disconnects it
- is maximally acyclic: addition of any edge creates a cycle.
Given a connected, undirected graph wih edge costs , a minimum spanning tree is a spanning tree of such that the sum of the edge costs in is minimized.
Cayley's Theorem: the complete graph on nodes has spnaninng trees (can't be solved by brute force).
Fundamental cycle: Let be a spanning tree of .
- for any non tree-edge contains a unique cyce, say .
- for any edge is a spanning tree
Observation: if , then is not an MST.
Fundamental cutset: let be a spanning tree of .
- for any tree edge has two connected components.
- Let denote corresponding cutset.
- For any dge is a spanning tree.
In any cutset, the edge with minimum weight must be in every MST.
The Greedy MST Algorithm
- red rule:
- let be a cycle with no red edge.
- select an uncolored edge of of max cost and color it red.
- blue rule:
- let be a cutset with no blue edges
- select an uncolored edge in of min cost and color it blue.
- greedy algorithm:
- apply the red and blue rules (nondeterministically), until all edges are colored. The blue edges form an MST.
- note: can stop once edges colored blue.
Greedy algorithm: proof of correctness Color invariant: the exists an MST containing every blue edge and no red edge Proof by indction on number of iterations.
- Base case: no edge colored -> every MST satisfies invariant
- Induction step (blue rule): suppose color invariant true before blue rule
- let be a chosen cutset, and let be edge colored blue.
- if , then still satisfiies invarant
- otherwise, consider fundamental cycle by adding to .
- let be another edge in .
- is uncolored and since
- not red
- blue rule not blue and
- Thus, satisfies invariant
- Induction step (red rule): suppose color invariant true before red rule
- let be chosen cycle, and let be edge colored red
- if , then still satisfies invariant
- Otherwise, consider fundamental cutset by deleting from .
- let be another edge in
- is uncolored and since
- not blue
- red rule not red and
- Thus, satisfies invariant.
Theorem: the greedy algorithm termiantes. Blue edges form an MST. Proof: we need to show that either the red or blue rule (or both) applies.
- suppose edge is left uncolored
- blue edge form a forest
- Case 1: both endpoints of are in the same blue tree apply red rule to cycle formed by adding to blue forrest.
- Case 2: both endpoints of are in different blue trees. apply blue rule to cutset induced by either of two blue trees.
Special cases are the Prim, Kruskal, reverse-delete, and more.
Prim's Algorithm
Initialize for any ndoe , Repeat times:
- add to a min-cost edge with exactly one endpoint in .
- Add the other endpoint to .
Theorem: Prim's algorithm computes an MST. Proof: special case of greedy algorithm (blue rule repeatedly applied to S) (by construction, edges in cutset are uncolored).
Implementation
Theorem: prim's algorithm can be implemented to run in time. Proof: implementation almost identical to Dijkstra's algorithm.
Prim (V,E,c): any node in V.
Fo each , ; . Create an empty priority queue . For each insert() While (is-not-empty())
- del-min()
- For each edge with :
- If ()
- Decrease-key()
- ; .
- If ()
Kruskal's Algorithm
Consider edges in ascending order of cost: add to tree unless it would create a cycle.
Theorem: kruskal's algorithm computes an MST. Proof: special case of greedy algorithms.
- Case 1: both endpoints of in same blue tree, color red by applying red rule to unique cycle (all other edges in cycle are blue).
- Case 2: both endpoints of in different blue trees color blue by applying blue rule to cutset defined by either tree (no edge in cutset has smaller cost since Kruskal chose it first)
Implemetation
Theorem: Kruskal's algorithm can be implemented to run in tme.
- Sort edges by cost
- Use union-find data structure to dynamically maintain connected commponents.
The algorithm:
Kruskal (V,E,c) Sort edges by cost and renumber so that . . For each to :
- If (find-set() find-set()) (are u and v in same component)
- Union() (make and in the same component). Return .
Reverse-Delete Algorithm
Start with all the edges in and consider them in descending order of cost: delete edge from unless it would disconnect .
Theorem: the reverse-delete algorithm computes an MST. Proof: special case of greedy algorithm:
- Case 1 (deleting edge does not disconnet ) apply red rule to cycle formed by adding (no edge in is more expensive since it would already been considered and deleted) to another path in between its two endpoints
- Case 2 (deleting edge disconnects ) apply blue rule ( is the only remaining edge in the cutset as all other edges in must haev been colored red / deleted) to cutset induced by either component.
Borůvka′s algorithm
Repeat until only one tree
- apply blue rule to cutset corresponding to each blue tree
- color all selected edges blue
Theorem: Borůvka′s algorithm computes the MST (assume edge costs are distinct) Proof: special case of greedy algorithm (repeatedly apply blue rule)
Implementation
Theorem: Borůvka′s algorithm can be implemented to run in tme. Proof:
- to implement a phase in time:
- compute connected components of blue edges
- for each edge , check if and are different components; if so, update each component's best edge in cutset
- phases since each phase (at least) halves total # components.
Single-Link Clustering
Clustering The goal: given a set of objects labeled partition into clusters so that objects in different clusters are far apart.
Applications:
- routing in mobile ad-hoc networks
- document cateogrization for web seraches
- similarity searching in medical image databases
- cluster celstial objects into stars, quasars, galaxies.
Clustering of maximum spacing k-clustering: divide objects into non-empty groups.
Distance function: numeric value specifying "closeness" of two obejcts:
- iff (identity of indiscernibles)
- (symmetry)
Spacing: min distance between any pair of points in different clusters Goal: given an integer , find a -clustiering of maximum spacing.
Greedy Clustering Algorithm
"Well-known" algorithm in science literature for single-linkage -clustering:
- form a graph on the node set , crresponding to clusters.
- find the closest pair of objects such that each objet is in a different cluster, and add an edge between them
- repeat times (until there are exactly clusters).
Key observation: this procedure is precisely Kruskal's algorithm (except we stop when there are connected components).
Alternative: find an MST and delete the longest edges.
Greedy Cluster Algorithm: Analysis Theorem: let denote the clustering formed by deleting the longets edges of an MST. Then, is a -clustering of max spacing. Proof:
- Let denote any other clustering
- Let and be in the same cluster in , say , but different clusters in , say and .
- Some edge () on path in spans two different clusters in . (this is the edge kruskal would have added next had we not stopped)
- Spacing of length of the ()st longets edge in MST.
- Edge () has length since it was added by Krusal
- Spacing of is since and are in different clusters
Linked from Algorithms