CSC2105: Algorithms Greedy Method
CSC2105: Algorithms Greedy Method
Greedy Method
Mashiour Rahman
[email protected]
American International University Bangladesh
The Greedy Method
The greedy method is a general algorithm design paradigm,
built on the following elements:
configurations: different choices, collections, or values to find
an objective function: a score assigned to configurations, which we
want to either maximize or minimize
Goal: Choose items with maximum total value but with weight at most W.
The value of an item is its benefit/weight ratio.
Objective: maximize x (b / w
iS
) i i i
Constraint: x
iS
Wi
“knapsack”
Solution:
• 1 ml of 5
Items:
1 2 3 4 5 • 2 ml of 3
• 6 ml of 4
Weight: 4 ml 8 ml 2 ml 6 ml 1 ml • 1 ml of 2
Benefit: $12 $32 $40 $30 $50 10 ml
Value: 3 4 20 5 50
($ per ml)
Mashiour AIUB::CSC2105::Algorithms Greedy 9
The Fractional Knapsack Algorithm
Algorithm fractionalKnapsack(S, W)
Machine 3
Machine 2
Machine 1
1 2 3 4 5 6 7 8 9
Machine 3
Machine 2
Machine 1
1 2 3 4 5 6 7 8 9
m 0 {no. of machines}
while T is not empty do
remove task i with smallest si
if there’s a machine j for i then
schedule i on machine j
else
m m + 1
schedule i on machine m
Greedy choice: consider tasks by their start time and use as few machines as
possible with this order.
Run time: O(n lg n). Why?
Correctness: Suppose there is a better schedule.
We can use k-1 machines
The algorithm uses k
Let i be first task scheduled on machine k
Machine i must conflict with k-1 other tasks
But that means there is no non-conflicting schedule using k-1 machines
Mashiour AIUB::CSC2105::Algorithms Greedy 13