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
E.g.: 20
---
$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
v1 v2 vn
...
w1 w2 wn
Fractional Knapsack Problem
Alg.: Fractional-Knapsack (W, v[n], w[n])
5. w w – xiwi
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)
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
We make a choice at each step
The choice depends on solutions to subproblems
Bottom up solution, from smaller to larger subproblems
Greedy algorithm
Make the greedy choice and THEN
Solve the subproblem arising after the choice is made
The choice we make may depend on previous choices,
but not on solutions to subproblems
Top down solution, problems decrease in size