FOA - Lecture - 11
FOA - Lecture - 11
Lecture 11
Today’s Outline
• Greedy Algorithms
• Knapsack Problem
1. 0-1 Knapsack Problem
2. Fractional Knapsack Problem
• Huffman Coding
Greedy Algorithms
• This approach is used to solve the optimization problems
• An optimization problem is one in which you want to find not just a
solution but the best solution.
• Example: You want to travel from point A to point B
• There may be more than one solution
1. By walk
2. By bike
3. By car
4. By train
5. By flight
Greedy Algorithms (cont.)
• But, there is a constraint in the problem that you have to cover the
journey within 12 hours.
• So, you can travel either by train or by flight to satisfy the constraint.
• Those solutions that satisfy the constraint given in the problem are
called feasible solutions.
• Now, if you want to cover this journey in minimum cost then choose
one solution from the feasible solutions. This solution will be called
optimal solution.
• For any problem, their can be only one optimal solution.
• Hence, there can be multiple solutions of a problem and there can be
multiple feasible solution but there is only one optimal solution.
Greedy Method
ALGORITHM GREEDY (P, n) //P is the problem of size n
for i = 1 to n
x = select(P[i]) //select one input from a problem
if x is a feasible solution
solution = solution + x //add all the feasible solutions
• So, the 3rd approach is the best in which the maximum profit per kg is
considered.
5 11
5 11
1
9
0
5 1 11
0 1 0 1
• We can see from the table, some alphabets are represents by 3-bits
and some are represented by 2-bits. This is called variable-length
coding.
• Now, what will be the cost/size of the message?
Huffman Coding – Variable Length Coding
(cont.)
Alphabet Frequency Code Size
A 3 001 3*3=9
B 5 10 5*2=10
C 6 11 6*2=12
D 4 01 4*2=8
E 2 000 2*3=6
• Size of the message is: 45-bits but we have to send chart/table along
with the data for decoding at receiver end. So, what will be the size of
the chart?
• 5*8 = 40 bits (for alphabets) and 12 bits (for codes), total are 52-bits
for chart or table.
• So, the total size/cost of the message is: 45 + 52 = 97 bits.