Lecture 6 Greedy Technique
Lecture 6 Greedy Technique
of Computer Algorithm
November 8, 2024
Greedy Method: Definition
Procedure GREEDY(A,n)
// A(1:n) contains the n inputs//
solution //initialize the solution to empty//
for i 1 to n do
x SELECT(A)
if FEASIBLE(solution,x)
then solution UNION(solution,x)
endif
repeat
return(solution)
end GREEDY
Question?
⚫ How can one tell if a greedy algorithm will solve a
particular optimization problem?
⚫ No general way to tell!!!
⚫ There are 2 ingredients that are exhibited by most
problems that lend themselves to a greedy strategy
– The Greedy Choice Property
– Optimal Substructure
⚫ Change making
⚫ knapsack algorithm
⚫ Huffman codes
⚫ Kruskal's MST algorithm
⚫ Prim's MST algorithm
⚫ Dijkstra's SSSP algorithm
⚫ Travelling salesman
⚫ …
maximize px
1i n
i i
subject to w x
1i n
i i M
and 0 xi 1, 1 I n
Item 3
Item 2 50
Item 1 30
20
10
20 $80
30
20 $100
10 $60
Total =$240
Price ($US) 20 30 66 40 60
weight (Lbs.) 10 20 30 40 50
Price ($US ) 20 30 66 40 60
weight (Lbs.) 10 20 30 40 50
half
Price ($US ) 20 30 66 40 60
weight (Lbs.) 10 20 30 40 50
price/weight 2 1 .5 2 .2 1 1 .2
⚫ Method 3 choose the most price/ weight first
– Total weight = 30 + 10 + 20 + 40 = 100
– Total Price = 66 + 20 + 30 + 48 = 164
80%
(x1,x2,x3) w x
i i px
i i