Professional Documents
Culture Documents
Course 5
Overview
Greedy Algorithms
Activity Selection
Huffman Trees
Greedy vs Dynamic Programming
Knapsack Problem
Greedy
DP
Generic problem
Greedy Algorithms
Efficient method to solve some optimization problems
The solutions to an optimization problem must satisfy a global
optimum
More difficult to verify
Simplification: choose the solution that looks best at each step
This is called a locally optimal solution
Advantages:
Simpler to build the solution
Less time / Better complexity
Disadvantage:
The locally optimal solution does not always lead to the globally
optimal solution
May not correctly solve the problem (but may provide good
approximations)
Greedy Algorithms (2)
At each step, we choose the best solution according to
the local optimum (greedy) choice
We abandon all the other possible solutions
The solving paths that are not considered by the greedy choice
are discarded!
RecursiveActivitySelection(s, f, i, n)
m = i +1
WHILE (m <= n AND s[m] < f[i])
m++ // find the activity with the earliest
// start time that starts after activity i finishes
IF (m <= n) THEN
RETURN {am} U RecursiveActivitySelection(s, f, m, n)
RETURN Φ
IterativeActivitySelection(s, f, n)
A = {a1}
i=1
FOR (m = 2..n)
IF (s[m] < f[i])
CONTINUE
ELSE
A = A U {am}
i=m
RETURN A
The cost of an encoding tree T for a set of keys K that have the
frequencies p:
Cost(T ) code _ length(k ) * p(k ) level (k , T ) * p(k )
kK kK
Initially:
0 1
W(a+r+ )=0.57 W(m+n+e)=0.41
0 1 0 1
W(a) W(r+ )=0.32 W(m+n)=0.16 W(e)
0 1 0 1
W(r) W( ) W(m) W(n)
Algorithm for building the Huffman Tree
On the whiteboard
Straightforward from the pseudocode
Decoding the File
Encoded text:
0010100011000101000111001101011
a n a „‟ a r e „‟ m e r e
We also need the Huffman tree
Starting from the first bit, we walk the tree from the root
to the first leaf we encounter
When at a leaf, append the key corresponding to that leaf to
the decoded text
Go to the root again and repeat until we reach the end of the
encoded text
Greedy Algorithms – Conclusions
Greedy algorithms that build the globally optimal solution can
be devised for some problems that have an optimal
substructure
Steps for devising a greedy algorithm:
Determine the optimal substructure
Develop a recursive solution
Prove that at any stage of recursion, one of the optimal choices
is the greedy choice. Therefore, it‟s always safe to make the
greedy choice
Show that all but one of the sub-problems resulting from the
greedy choice are empty
Develop a recursive greedy algorithm
Convert it to an iterative algorithm
Greedy Algorithms – Conclusions (2)
Properties for optimization problems that accept correct
greedy solutions:
Optimal substructure
Greedy choice property
http://www.math.fau.edu/locke/Greedy.htm