16 Greedy Algorithms
16 Greedy Algorithms
16 Greedy Algorithms
There are n items: the i-th item has value vi and weight
wi
Goal:
wixi W and
xivi is maximum
Fractional Knapsack - Example
20
E.g.: ---
$80
Item 3 30 +
Item 2 50 50
20 $100
Item 1 30
20 +
10 10 $60
Pick the item with the maximum value per pound vi/wi
5. w w – x i wi
O(lg n)
O(lg n)
O(lg n)
Cost of a Tree T
For each character c in the alphabet C
let f(c) be the frequency of c in the file
let dT(c) be the depth of c in the tree
It is also the length of the codeword. Why?
Let B(T) be the number of bits required to
encode the file (called the cost of T)
optimal code
A min-priority queue Q, is used to identify the two
Encoding:
Given the characters and their frequencies, perform the
algorithm and generate a code. Write the characters
using the code
Decoding:
Given the Huffman tree, figure out what each character
is (possible because of prefix property)
Application on Huffman code
Both the .mp3 and .jpg file formats use
Huffman coding at one stage of the
compression
Dynamic Programming vs. Greedy
Algorithms
Dynamic programming