Lecture 16 17
Lecture 16 17
Lecture 16 17
2
Greedy Algorithm
We will study
• The activity selection problem
• Element of a greedy strategy
• The problem of generating Huffman codes
4
Greedy Algorithm
•Algorithm Greedy(a,n)
//a[1:n] contains the n inputs.
{
Solution :=0;
For i=1 to n do
{
X:=select(a);
If Feasible(solution, x) then
Solution :=Union(solution,x);
}
Return solution;
}
5
Fractional Knapsack Problem
6
Fractional Knapsack Problem
Knapsack capacity: W
There are n items: the i-th item has value
vi and weight wi
Goal:
find xi such that for all 0 xi 1, i =
1, 2, .., n
wixi W and
xivi is maximum
7
Fractional Knapsack Problem
Alg.: Fractional-Knapsack (W, v[n], w[n])
1. While w > 0 and as long as there are items remaining
5. w w – xiwi
E.g.: 20
---
$80
Item 3 30 +
Item 2 50 50
20 $100
Item 1 30
20 +
10 10 $60
9
Fractional Knapsack Problem
Greedy strategy 1:
Pick the item with the maximum value
E.g.:
W=1
w1 = 100, v1 = 2
w2 = 1, v2 = 1
Taking from the item with the maximum value:
Total value taken = v1/w1 = 2/100
Smaller than what the thief can take if choosing the other item
Total value (choose item 2) = v2/w2 = 1
10
Fractional Knapsack Problem
Greedy strategy 2:
Pick the item with the maximum value per pound vi/wi
If the supply of that element is exhausted and the thief can
carry more: take as much as possible from the item with
the next greatest value per pound
It is good to order items based on their value per pound
11
REFERENCES
Text books:
• Cormen, Leiserson, Rivest, Stein, “Introduction to Algorithms”, Prentice Hall of India, 3rd edition 2012.
problem, Graph coloring.
Websites:
• https://www.tutorialspoint.com/data_structures_algorithms/kruskals_spanning_tree_algorithm.htm
• https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
THANK YOU