Professional Documents
Culture Documents
Greedy Algorithms
Greedy Algorithm makes the choice that looks best at the
moment. May not lead to the optimal solution.
An activity-selection problem
Given a set S = {a1 , a2 , .., an } of activities that wish to use a
resource.
This resource can be used by one activity at a time (no
overlapping).
Each activity ai has a start time si and a finish time fi .
Two activities ai and aj are compatible if the intervals [si , fi ] and
[sj , fj ] do not overlap.
Assume that the activities are ordered by increasing finish time
f 1 ≤ f2 ≤ · · · ≤ fn .
Chapter 16 2
Greedy-Activity-Selection(s, f )
1 XXn ←− length[s]
2XXA ←− {a1 }
3XXi ←− 1
4XXfor m ←− 2 to n
5 XXXXdo if sm ≥ fi
6 XXXXXXthen A ←− A ∪ {am }
7XXXXXXXXi ←− m
8XXreturn A
Huffman Codes
Coding scheme based on frequency of occurrence of each
character. It is efficient in data compression.
Let a data file consist of the characters a, b, c and d.
Represent each character using 2 bits (a : 00, b : 01, c : 10, d : 11).
Using this encoding a data file with n of these characters will
always be encoded using 2n bits.
Suppose that we know more about the data stream (i.e. the
frequency of occurrence of each character).
Frequencies of a, b, c, d are 10, 2, 8, 1 respectively
Change the encoding to a : 0, c : 10, b : 110, d : 111
Encoding of abacacd requires 14 bits with the regular code and
1+3+1+2+1+2+3 = 13 bits with the variable length encoding.
Chapter 16 9
HUFFMAN(C)
1XXn ←− |C|
2XXQ ←− C
3 XXfor i ←− 1 to n − 1
4XXXXdo allocate a new node z
5XXXXXXlef t[z] ←− x ←− EXT RACT − M IN (Q)
6XXXXXXright[z] ←− y ←− EXT RACT − M IN (Q)
7 XXXXXXf [z] ←− f [x] + f [y]
8 XXXXXXIN SERT (Q, z)
9XXreturn EXT RACT − M IN (Q)
B(T ) − B(T 0 ) = f (x)dT (x) + f (a)dT (a) − f (x)dT 0 (x) − f (a)dT 0 (a)
= f (x)dT (x) + f (a)dT (a) − f (x)dT (a) − f (a)dT (x)
= −f (x)(dT (a) − dT (x)) + f (a)(dT (a) − dT (x))
= (f (a) − f (x))(dT (a) − dT (x)) ≥ 0