03 Greedy Algorithms
03 Greedy Algorithms
Greedy Algorithms
EL Moukhtar ZEMMOURI
ENSAM – Meknès
Example 1: Scheduling
Activity selection problem
Scheduling : activity selection problem
DP approach
The optimal substructure
• *!" = the set of activities starting after !! finishes and finishing before !" starts.
o That is an optimal solution *!" must also include optimal solutions to the two subproblems for $!$
and $$" .
• We have :
o - ., / = 0 if *!" = ∅
• So :
o Sort the activities such that ## ≤ #& ≤ ⋯ ≤ #)
o Choose !#
o Then you have one subproblem to solve: set of activities that start after !# finishes.
Greedy algorithm
activity_selection_greedy (a, s, f, n)
Exercises
• Suppose that instead of selecting the first activity to finish, you instead select the
last activity to start that is compatible with all previously selected activities.
Does this greedy choice produce an optimal solution?
Data compression
Not valid !
E. Zemmouri, ENSAM - Meknès 14
Huffman Coding
• Huffman proposed (in 1952) a greedy algorithm that constructs an optimal prefix-
free code called a Huffman code.
• The algorithm builds a binary tree based on the frequencies of the characters
o Each character’s codeword can be read by following a path from the root to the
corresponding node.
o A move to the left corresponds to bit 0, and a move to the right corresponds to bit 1.
• Algorithm :
o Initially, each character is represented by a node whose weight is the frequency of this
character.
o Then at each step two nodes with minimum weights are combined by creating a new
node whose weight is the sum of the weights of the original nodes.
o The process continues until all nodes have been combined.
huffman (characters)
// characters : a hash table containing (char, frequency) pairs
n = charcters.size
for i = 1 à n-1
x = queue.extract() // extract a first node with min frequency
y = queue.extract() // extract a second node with min frequency
z = Node ('_’ , x.frequency + y.frequency) // create new node with sum frequencies
z.left = x
z.right = y
queue.insert (z) // insert the new node into the queue
root = queue.extract()
return root // return the root of the constructed binary tree