SlideShare a Scribd company logo
1 of 36
Greedy Algorithms
2
Optimization problems
 An optimization problem is one in which you want
to find, not just a solution, but the best solution
 A “greedy algorithm” sometimes works well for
optimization problems
 A greedy algorithm works in phases. At each
phase:
» You take the best you can get right now, without regard
for future consequences
» You hope that by choosing a local optimum at each
step, you will end up at a global optimum
3
Example: Counting money
 Suppose you want to count out a certain amount of
money, using the fewest possible bills and coins
 A greedy algorithm would do this would be:
At each step, take the largest possible bill or coin
that does not overshoot
» Example: To make $6.39, you can choose:
• a $5 bill
• a $1 bill, to make $6
• a 25¢ coin, to make $6.25
• A 10¢ coin, to make $6.35
• four 1¢ coins, to make $6.39
 For US money, the greedy algorithm always gives
the optimum solution
A failure of the greedy algorithm
 In some (fictional) monetary system, “krons” come
in 1 kron, 7 kron, and 10 kron coins
 Using a greedy algorithm to count out 15 krons,
you would get
» A 10 kron piece
» Five 1 kron pieces, for a total of 15 krons
» This requires six coins
 A better solution would be to use two 7 kron pieces
and one 1 kron piece
» This only requires three coins
 The greedy algorithm results in a solution, but not
in an optimal solution
Overview
 Problems exhibit optimal substructure (like DP).
 Problems also exhibit the greedy-choice property.
» When we have a choice to make, make the one that looks
best right now.
» Make a locally optimal choice in hope of getting a globally
optimal solution.
 Application:
» Shortest path
» MST
» Huffman code
A scheduling problem
 You have to run nine jobs, with running times of 3, 5, 6, 10, 11,
14, 15, 18, and 20 minutes
 You have three processors on which you can run these jobs
 You decide to do the longest-running jobs first, on whatever
processor is available
20
18
15 14
11
10
6
5
3
P1
P2
P3
 Time to completion: 18 + 11 + 6 = 35 minutes
 This solution isn’t bad, but we might be able to do better
Another approach
 What would be the result if you ran the shortest job first?
 Again, the running times are 3, 5, 6, 10, 11, 14, 15, 18, and 20
minutes
 That wasn’t such a good idea; time to completion is now
6 + 14 + 20 = 40 minutes
 Note, however, that the greedy algorithm itself is fast
» All we had to do at each stage was pick the minimum or maximum
20
18
15
14
11
10
6
5
3
P1
P2
P3
An optimum solution
 This solution is clearly optimal
 There may be other optimal solutions
 How do we find such a solution?
» One way: Try all possible assignments of jobs to processors
» Unfortunately, this approach can take exponential time
 Better solutions do exist:
20
18
15
14
11
10 6
5
3
P1
P2
P3
Interval Scheduling
Interval Scheduling
 Interval scheduling.
» Job j starts at sj and finishes at fj.
» Two jobs compatible if they don't overlap.
» Goal: find maximum subset of mutually compatible jobs.
Time
0 1 2 3 4 5 6 7 8 9 10 11
f
g
h
e
a
b
c
d
Interval Scheduling: Greedy Algorithm
 Greedy templates: Consider jobs in some natural order.
Take each job provided it's compatible with the ones
already taken.
» [Earliest start time] Consider jobs in ascending order of sj.
» [Earliest finish time] Consider jobs in ascending order of fj.
» [Shortest interval] Consider jobs in ascending order of fj - sj.
» [Fewest conflicts] For each job j, count the number of
conflicting jobs cj. Schedule in ascending order of cj.
Interval Scheduling: Greedy Algorithm
 Greedy template: Consider jobs in some natural order.
Take each job provided it's compatible with the ones
already taken.
Counter example for earliest start time
Counter example for shortest interval
Counter example for fewest conflicts
Interval Scheduling: Greedy Algorithm
Sort jobs by finish times so that f1  f2  ...  fn.
R  all requests i
A  
while R   do
Choose a request i ∈ R that has the smallest finishing time
A  A  {i}
Delete all requests from R that are not compatible with
request i
endWhile
return A
 Greedy algorithm: Consider jobs in increasing order
of finish time. Take each job provided it's
compatible with the ones already taken.
Example
 Running time = O(n log n) sorting time of finishing
time of n jobs.
» Remember job j* that was added last to A.
» Job j is compatible with A if sj  fj*.
» O(n) time to go through the sorted list of n jobs in
the while loop
Interval Scheduling: Greedy Algorithm
Interval Scheduling: Analysis
 Theorem. Greedy algorithm is optimal.
 Pf. (by contradiction)
» Assume greedy is not optimal, and let's see what happens.
» Let i1, i2, ... ik denote set of jobs selected by greedy.
» Let j1, j2, ... jm denote set of jobs in the optimal solution with
i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r.
j1 j2 jr
i1 i2 ir ir+1
. . .
Greedy:
OPT: jr+1
why not replace job jr+1
with job ir+1 in OPT?
job ir+1 finishes before jr+1
Interval Scheduling: Analysis
 Theorem. Greedy algorithm is optimal.
 Pf. (by contradiction)
» Assume greedy is not optimal, and let's see what happens.
» Let i1, i2, ... ik denote set of jobs selected by greedy.
» Let j1, j2, ... jm denote set of jobs in the optimal solution with
i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r.
j1 j2 jr
i1 i2 ir ir+1
. . .
Greedy:
OPT:
solution still feasible and
optimal, but contradicts
maximality of r.
jr+1
job ir+1 finishes with jr+1
Interval Scheduling: Analysis
 Theorem. Greedy algorithm is optimal.
 Pf. (by contradiction)
» Assume greedy is not optimal, and let's see what happens.
» Let i1, i2, ... ik denote set of jobs selected by greedy.
» Let j1, j2, ... jm denote set of jobs in the optimal solution with
i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r.
j1 j2 jr
i1 i2 ir ir+1
. . .
Greedy:
OPT: jr+1
job ir+1 finishes after jr+1
Greedy will select job jr+1 before job ir+1.
Interval Partitioning
 Interval scheduling so far is using a single
resource.
 Extension: What if we have multiple resources for
scheduling tasks?
 Assumption: all resources are equivalent
Interval Partitioning
 Interval partitioning.
» Lecture j starts at sj and finishes at fj.
» Goal: find minimum number of classrooms to schedule
all lectures so that no two lectures occur at the same
time in the same room.
 Ex: This schedule uses 4 classrooms to schedule
10 lectures.
Time
9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30
h
c
b
a
e
d g
f i
j
3 3:30 4 4:30
1
2
3
4
Interval Partitioning
 Interval partitioning.
» Lecture j starts at sj and finishes at fj.
» Goal: find minimum number of classrooms to schedule
all lectures
so that no two occur at the same time in the same room.
 Ex: This schedule uses only 3.
Time
9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30
h
c
a e
f
g i
j
3 3:30 4 4:30
d
b
1
2
3
Interval Partitioning: Lower Bound on Optimal Solution
 Def. The depth of a set of open intervals is the
maximum number that contain all concurrent
intervals at any given time.
 Key observation. Number of classrooms needed 
depth.
 Ex: Depth of schedule below = 3  schedule
below is optimal.
 Q. Does there always exist a schedule equal to
depth of intervals? Time
9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30
h
c
a e
f
g i
j
3 3:30 4 4:30
d
b
a, b, c all contain 9:30
1
2
3
23
Interval Partitioning: Lower Bound on
Optimal Solution
 Def. The depth of a set of open intervals is the
maximum number that contain all concurrent
intervals at any given time.
 Key observation. Number of classrooms needed 
depth.
 Ex: Depth of schedule below = 3  schedule
below is optimal.
 Q. Does there always exist a schedule equal to Time
9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30
h
c
a e
f
g i
j
3 3:30 4 4:30
d
b
a, b, c all contain 9:30
1
2
3
24
Interval Partitioning: Greedy
Algorithm
 Greedy algorithm. Consider lectures in increasing
order of start time: assign lecture to any
compatible classroom.
 Implementation. O(n log n).
Sort intervals by starting time so that s1  s2  ...  sn.
d  0
for j = 1 to n {
if (lecture j is compatible with some classroom k)
schedule lecture j in classroom k
else
allocate a new classroom d + 1
schedule lecture j in classroom d + 1
d  d + 1
}
number of allocated classrooms
25
Interval Partitioning: Greedy Analysis
 Observation. Greedy algorithm never schedules
two incompatible lectures in the same classroom.
 Theorem. Greedy algorithm is optimal.
 Pf.
» Let d = number of classrooms that the greedy algorithm
allocates.
» Classroom d is opened because we needed to schedule a
job, say j, that is incompatible with all d-1 other
classrooms.
» These d-1 jobs each end after sj (because of
incompatible).
» Since we sorted by start time, all these incompatibilities
4.2 Scheduling to Minimize
Lateness
What if all jobs do not have predefined fixed starting time?
Use a single resource to complete all jobs one after another
27
Scheduling to Minimizing Lateness
 Minimizing lateness problem.
» Single resource processes one job at a time.
» Job j requires tj units of processing time and is due at time dj.
» If j starts at time sj, it finishes at time fj = sj + tj.
» Lateness: j = max { 0, fj - dj }.
» Goal: schedule all jobs to minimize maximum lateness L =
max j.
 Ex:
dj 6
tj 3
1
8
2
2
9
1
3
9
4
4
14
3
5
15
2
6
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
d5 = 14
d2 = 8 d6 = 15 d1 = 6 d4 = 9
d3 = 9
lateness = 0
lateness = 2 max lateness = 6
28
Minimizing Lateness: Greedy
Algorithms
 Greedy template. Consider jobs in some order.
» [Shortest processing time first] Consider jobs in ascending
order of processing time tj.
» [Earliest deadline first] Consider jobs in ascending order of
deadline dj.
» [Smallest slack] Consider jobs in ascending order of slack dj
- tj.
29
 Greedy template. Consider jobs in some order.
» [Shortest processing time first] Consider jobs in ascending
order of processing time tj.
» [Smallest slack] Consider jobs in ascending order of slack dj
- tj.
counterexample
counterexample
dj
tj
100
1
1
10
10
2
dj
tj
2
1
1
10
10
2
Minimizing Lateness: Greedy
Algorithms
30
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
d5 = 14
d2 = 8 d6 = 15
d1 = 6 d4 = 9
d3 = 9
max lateness = 1
Sort n jobs by deadline so that d1  d2  …  dn
t  0
for j = 1 to n
Assign job j to interval [t, t + tj]
sj  t, fj  t + tj
t  t + tj
output intervals [sj, fj]
Minimizing Lateness: Greedy
Algorithm
 Greedy algorithm. Earliest deadline first.
dj 6
tj 3
1
8
2
2
9
1
3
9
4
4
14
3
5
15
2
6
31
Minimizing Lateness: No Idle Time
 Observation. There exists an optimal schedule with no
idle time.
 Observation. The greedy schedule has no idle time.
0 1 2 3 4 5 6
d = 4 d = 6
7 8 9 10 11
d = 12
0 1 2 3 4 5 6
d = 4 d = 6
7 8 9 10 11
d = 12
32
Minimizing Lateness: Inversions
 Def. Given a schedule S, an inversion is a pair of jobs i
and j such that:
di < dj but j scheduled before i.
 Observation. Greedy schedule has no inversions and
no idle time.
i
j
before swap
fi
inversion
[ as before, we assume jobs are numbered so that d1  d2  …  dn ]
33
Minimizing Lateness: Inversions
 Def. Given a schedule S, an inversion is a pair of jobs i and j
such that: i < j but j scheduled before i.
 Claim. Swapping two consecutive, inverted jobs reduces the
number of inversions by one and does not increase the max
lateness.
 Pf. Let  be the lateness before the swap, and let  ' be it
afterwards.
»  'k = k for all k  i, j


j  
fj  dj (definition)
 fi  dj ( j finishes at time fi )
 fi  di (i  j)
 i (definition)
i
j
i j
before swap
after swap
f'j
fi
inversion
34
Claim. All schedules with no inversion and no idle time have the same maximum
lateness.
Pf. Two such schedules must differ in the order in which jobs with identical
deadlines are scheduled.
Jobs with this same deadline are scheduled consecutively.
The last of these jobs have the largest lateness, not depend on the order of these
jobs.
35
Minimizing Lateness: Analysis of
Greedy Algorithm
 Theorem. Greedy schedule S is optimal.
 Pf. Define S* to be an optimal schedule that has the
fewest number of inversions, and let's see what
happens.
» Can assume S* has no idle time.
» If S* has no inversions, then S = S* (greedy schedule result S
is also with no inversions and idle time)
» If S* has an inversion, let i-j be an adjacent inversion.
• swapping i and j does not increase the maximum lateness and strictly
decreases the number of inversions
• this contradicts definition of S* ▪
36
Greedy Analysis Strategies
 Greedy algorithm stays ahead. Show that after each
step of the greedy algorithm, its solution is at least
as good as any other algorithm's.
 Structural. Discover a simple "structural" bound
asserting that every possible solution must have a
certain value. Then show that your algorithm
always achieves this bound.
 Exchange argument. Gradually transform any
solution to the one found by the greedy algorithm
without hurting its quality.

More Related Content

What's hot

What's hot (20)

String matching algorithm
String matching algorithmString matching algorithm
String matching algorithm
 
Chapter 4 (final)
Chapter 4 (final)Chapter 4 (final)
Chapter 4 (final)
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Disjoint sets union, find
Disjoint sets  union, findDisjoint sets  union, find
Disjoint sets union, find
 
Daa notes 3
Daa notes 3Daa notes 3
Daa notes 3
 
Theory of Computation Unit 1
Theory of Computation Unit 1Theory of Computation Unit 1
Theory of Computation Unit 1
 
Primality
PrimalityPrimality
Primality
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
String matching algorithms
String matching algorithmsString matching algorithms
String matching algorithms
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
KMP Pattern Matching algorithm
KMP Pattern Matching algorithmKMP Pattern Matching algorithm
KMP Pattern Matching algorithm
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
AI: AI & Searching
AI: AI & SearchingAI: AI & Searching
AI: AI & Searching
 
0 1 knapsack using branch and bound
0 1 knapsack using branch and bound0 1 knapsack using branch and bound
0 1 knapsack using branch and bound
 
N queen problem
N queen problemN queen problem
N queen problem
 
Np complete
Np completeNp complete
Np complete
 
Daa notes 1
Daa notes 1Daa notes 1
Daa notes 1
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 

Similar to 12-greedy.ppt

Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexity
Madhu Niket
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
hodcsencet
 
Analysis Of Algorithms I
Analysis Of Algorithms IAnalysis Of Algorithms I
Analysis Of Algorithms I
Sri Prasanna
 

Similar to 12-greedy.ppt (20)

04greedy 2x2
04greedy 2x204greedy 2x2
04greedy 2x2
 
Job scheduling
Job schedulingJob scheduling
Job scheduling
 
data structures and algorithms Unit 4
data structures and algorithms Unit 4data structures and algorithms Unit 4
data structures and algorithms Unit 4
 
Greedy method
Greedy methodGreedy method
Greedy method
 
Exam100412
Exam100412Exam100412
Exam100412
 
Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexity
 
Flowshop scheduling
Flowshop schedulingFlowshop scheduling
Flowshop scheduling
 
Design and analysis of algorithms
Design and analysis of algorithmsDesign and analysis of algorithms
Design and analysis of algorithms
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
Analysis Of Algorithms I
Analysis Of Algorithms IAnalysis Of Algorithms I
Analysis Of Algorithms I
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
Approximation algorithms
Approximation algorithmsApproximation algorithms
Approximation algorithms
 
Comparing Different Job Scheduling Heuristics
Comparing Different Job Scheduling HeuristicsComparing Different Job Scheduling Heuristics
Comparing Different Job Scheduling Heuristics
 
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
TIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMSTIME EXECUTION   OF  DIFFERENT SORTED ALGORITHMS
TIME EXECUTION OF DIFFERENT SORTED ALGORITHMS
 
Exam110121
Exam110121Exam110121
Exam110121
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Scheduling jobs on identical parallel machines
Scheduling jobs on identical parallel machinesScheduling jobs on identical parallel machines
Scheduling jobs on identical parallel machines
 
Approximation Algorithms Part Two: More Constant factor approximations
Approximation Algorithms Part Two: More Constant factor approximationsApproximation Algorithms Part Two: More Constant factor approximations
Approximation Algorithms Part Two: More Constant factor approximations
 
Algorithm big o
Algorithm big oAlgorithm big o
Algorithm big o
 

More from ASVKVinayak (8)

LECTURE 0.pptx
LECTURE 0.pptxLECTURE 0.pptx
LECTURE 0.pptx
 
questions.pptx
questions.pptxquestions.pptx
questions.pptx
 
1_Introduction.pptx
1_Introduction.pptx1_Introduction.pptx
1_Introduction.pptx
 
Digital Logic-Lecture19.pptx
Digital Logic-Lecture19.pptxDigital Logic-Lecture19.pptx
Digital Logic-Lecture19.pptx
 
26.ppt
26.ppt26.ppt
26.ppt
 
interdependence.ppt
interdependence.pptinterdependence.ppt
interdependence.ppt
 
Disaster management Cyclone.pptx
Disaster management Cyclone.pptxDisaster management Cyclone.pptx
Disaster management Cyclone.pptx
 
LOGIC DESIGN-Lecture24.pptx
LOGIC DESIGN-Lecture24.pptxLOGIC DESIGN-Lecture24.pptx
LOGIC DESIGN-Lecture24.pptx
 

Recently uploaded

Minimalist Orange Portfolio by Slidesgo.pptx
Minimalist Orange Portfolio by Slidesgo.pptxMinimalist Orange Portfolio by Slidesgo.pptx
Minimalist Orange Portfolio by Slidesgo.pptx
balqisyamutia
 
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
HyderabadDolls
 
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
gajnagarg
 
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
wpkuukw
 
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman MuscatAbortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
Abortion pills in Kuwait Cytotec pills in Kuwait
 
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
nirzagarg
 
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
Nitya salvi
 

Recently uploaded (20)

How to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdfHow to Create a Productive Workspace Trends and Tips.pdf
How to Create a Productive Workspace Trends and Tips.pdf
 
Sweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptxSweety Planet Packaging Design Process Book.pptx
Sweety Planet Packaging Design Process Book.pptx
 
Minimalist Orange Portfolio by Slidesgo.pptx
Minimalist Orange Portfolio by Slidesgo.pptxMinimalist Orange Portfolio by Slidesgo.pptx
Minimalist Orange Portfolio by Slidesgo.pptx
 
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
Madhyamgram \ (Genuine) Escort Service Kolkata | Service-oriented sexy call g...
 
LANDSCAPE ARCHITECTURE PORTFOLIO - MAREK MITACEK
LANDSCAPE ARCHITECTURE PORTFOLIO - MAREK MITACEKLANDSCAPE ARCHITECTURE PORTFOLIO - MAREK MITACEK
LANDSCAPE ARCHITECTURE PORTFOLIO - MAREK MITACEK
 
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In eluru [ 7014168258 ] Call Me For Genuine Models We ...
 
Abu Dhabi Call girls Service0556255850 Call girls in Abu Dhabi
Abu Dhabi Call girls Service0556255850 Call girls in Abu DhabiAbu Dhabi Call girls Service0556255850 Call girls in Abu Dhabi
Abu Dhabi Call girls Service0556255850 Call girls in Abu Dhabi
 
Call Girls Jalaun Just Call 8617370543 Top Class Call Girl Service Available
Call Girls Jalaun Just Call 8617370543 Top Class Call Girl Service AvailableCall Girls Jalaun Just Call 8617370543 Top Class Call Girl Service Available
Call Girls Jalaun Just Call 8617370543 Top Class Call Girl Service Available
 
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
一比一定(购)卡尔顿大学毕业证(CU毕业证)成绩单学位证
 
Just Call Vip call girls Kasganj Escorts ☎️8617370543 Two shot with one girl ...
Just Call Vip call girls Kasganj Escorts ☎️8617370543 Two shot with one girl ...Just Call Vip call girls Kasganj Escorts ☎️8617370543 Two shot with one girl ...
Just Call Vip call girls Kasganj Escorts ☎️8617370543 Two shot with one girl ...
 
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman MuscatAbortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
Abortion Pills in Oman (+918133066128) Cytotec clinic buy Oman Muscat
 
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In Sonipat [ 7014168258 ] Call Me For Genuine Models W...
 
Dahisar Comfortable Call Girls ,09167354423,Mira Road Model Call Girls
Dahisar Comfortable Call Girls ,09167354423,Mira Road Model Call GirlsDahisar Comfortable Call Girls ,09167354423,Mira Road Model Call Girls
Dahisar Comfortable Call Girls ,09167354423,Mira Road Model Call Girls
 
Just Call Vip call girls Fatehpur Escorts ☎️8617370543 Two shot with one girl...
Just Call Vip call girls Fatehpur Escorts ☎️8617370543 Two shot with one girl...Just Call Vip call girls Fatehpur Escorts ☎️8617370543 Two shot with one girl...
Just Call Vip call girls Fatehpur Escorts ☎️8617370543 Two shot with one girl...
 
NO1 Top Pakistani Amil Baba Real Amil baba In Pakistan Najoomi Baba in Pakist...
NO1 Top Pakistani Amil Baba Real Amil baba In Pakistan Najoomi Baba in Pakist...NO1 Top Pakistani Amil Baba Real Amil baba In Pakistan Najoomi Baba in Pakist...
NO1 Top Pakistani Amil Baba Real Amil baba In Pakistan Najoomi Baba in Pakist...
 
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
Call Girls In Ratnagiri Escorts ☎️8617370543 🔝 💃 Enjoy 24/7 Escort Service En...
 
Aminabad * High Profile Escorts Service in Lucknow Phone No 9548273370 Elite ...
Aminabad * High Profile Escorts Service in Lucknow Phone No 9548273370 Elite ...Aminabad * High Profile Escorts Service in Lucknow Phone No 9548273370 Elite ...
Aminabad * High Profile Escorts Service in Lucknow Phone No 9548273370 Elite ...
 
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
Nishatganj ? Book Call Girls in Lucknow | Book 9548273370 Extreme Naughty Cal...
 
Jordan_Amanda_DMBS202404_PB1_2024-04.pdf
Jordan_Amanda_DMBS202404_PB1_2024-04.pdfJordan_Amanda_DMBS202404_PB1_2024-04.pdf
Jordan_Amanda_DMBS202404_PB1_2024-04.pdf
 
TRose UXPA Experience Design Concord .pptx
TRose UXPA Experience Design Concord .pptxTRose UXPA Experience Design Concord .pptx
TRose UXPA Experience Design Concord .pptx
 

12-greedy.ppt

  • 2. 2 Optimization problems  An optimization problem is one in which you want to find, not just a solution, but the best solution  A “greedy algorithm” sometimes works well for optimization problems  A greedy algorithm works in phases. At each phase: » You take the best you can get right now, without regard for future consequences » You hope that by choosing a local optimum at each step, you will end up at a global optimum
  • 3. 3 Example: Counting money  Suppose you want to count out a certain amount of money, using the fewest possible bills and coins  A greedy algorithm would do this would be: At each step, take the largest possible bill or coin that does not overshoot » Example: To make $6.39, you can choose: • a $5 bill • a $1 bill, to make $6 • a 25¢ coin, to make $6.25 • A 10¢ coin, to make $6.35 • four 1¢ coins, to make $6.39  For US money, the greedy algorithm always gives the optimum solution
  • 4. A failure of the greedy algorithm  In some (fictional) monetary system, “krons” come in 1 kron, 7 kron, and 10 kron coins  Using a greedy algorithm to count out 15 krons, you would get » A 10 kron piece » Five 1 kron pieces, for a total of 15 krons » This requires six coins  A better solution would be to use two 7 kron pieces and one 1 kron piece » This only requires three coins  The greedy algorithm results in a solution, but not in an optimal solution
  • 5. Overview  Problems exhibit optimal substructure (like DP).  Problems also exhibit the greedy-choice property. » When we have a choice to make, make the one that looks best right now. » Make a locally optimal choice in hope of getting a globally optimal solution.  Application: » Shortest path » MST » Huffman code
  • 6. A scheduling problem  You have to run nine jobs, with running times of 3, 5, 6, 10, 11, 14, 15, 18, and 20 minutes  You have three processors on which you can run these jobs  You decide to do the longest-running jobs first, on whatever processor is available 20 18 15 14 11 10 6 5 3 P1 P2 P3  Time to completion: 18 + 11 + 6 = 35 minutes  This solution isn’t bad, but we might be able to do better
  • 7. Another approach  What would be the result if you ran the shortest job first?  Again, the running times are 3, 5, 6, 10, 11, 14, 15, 18, and 20 minutes  That wasn’t such a good idea; time to completion is now 6 + 14 + 20 = 40 minutes  Note, however, that the greedy algorithm itself is fast » All we had to do at each stage was pick the minimum or maximum 20 18 15 14 11 10 6 5 3 P1 P2 P3
  • 8. An optimum solution  This solution is clearly optimal  There may be other optimal solutions  How do we find such a solution? » One way: Try all possible assignments of jobs to processors » Unfortunately, this approach can take exponential time  Better solutions do exist: 20 18 15 14 11 10 6 5 3 P1 P2 P3
  • 10. Interval Scheduling  Interval scheduling. » Job j starts at sj and finishes at fj. » Two jobs compatible if they don't overlap. » Goal: find maximum subset of mutually compatible jobs. Time 0 1 2 3 4 5 6 7 8 9 10 11 f g h e a b c d
  • 11. Interval Scheduling: Greedy Algorithm  Greedy templates: Consider jobs in some natural order. Take each job provided it's compatible with the ones already taken. » [Earliest start time] Consider jobs in ascending order of sj. » [Earliest finish time] Consider jobs in ascending order of fj. » [Shortest interval] Consider jobs in ascending order of fj - sj. » [Fewest conflicts] For each job j, count the number of conflicting jobs cj. Schedule in ascending order of cj.
  • 12. Interval Scheduling: Greedy Algorithm  Greedy template: Consider jobs in some natural order. Take each job provided it's compatible with the ones already taken. Counter example for earliest start time Counter example for shortest interval Counter example for fewest conflicts
  • 13. Interval Scheduling: Greedy Algorithm Sort jobs by finish times so that f1  f2  ...  fn. R  all requests i A   while R   do Choose a request i ∈ R that has the smallest finishing time A  A  {i} Delete all requests from R that are not compatible with request i endWhile return A  Greedy algorithm: Consider jobs in increasing order of finish time. Take each job provided it's compatible with the ones already taken.
  • 15.  Running time = O(n log n) sorting time of finishing time of n jobs. » Remember job j* that was added last to A. » Job j is compatible with A if sj  fj*. » O(n) time to go through the sorted list of n jobs in the while loop Interval Scheduling: Greedy Algorithm
  • 16. Interval Scheduling: Analysis  Theorem. Greedy algorithm is optimal.  Pf. (by contradiction) » Assume greedy is not optimal, and let's see what happens. » Let i1, i2, ... ik denote set of jobs selected by greedy. » Let j1, j2, ... jm denote set of jobs in the optimal solution with i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r. j1 j2 jr i1 i2 ir ir+1 . . . Greedy: OPT: jr+1 why not replace job jr+1 with job ir+1 in OPT? job ir+1 finishes before jr+1
  • 17. Interval Scheduling: Analysis  Theorem. Greedy algorithm is optimal.  Pf. (by contradiction) » Assume greedy is not optimal, and let's see what happens. » Let i1, i2, ... ik denote set of jobs selected by greedy. » Let j1, j2, ... jm denote set of jobs in the optimal solution with i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r. j1 j2 jr i1 i2 ir ir+1 . . . Greedy: OPT: solution still feasible and optimal, but contradicts maximality of r. jr+1 job ir+1 finishes with jr+1
  • 18. Interval Scheduling: Analysis  Theorem. Greedy algorithm is optimal.  Pf. (by contradiction) » Assume greedy is not optimal, and let's see what happens. » Let i1, i2, ... ik denote set of jobs selected by greedy. » Let j1, j2, ... jm denote set of jobs in the optimal solution with i1 = j1, i2 = j2, ..., ir = jr for the largest possible value of r. j1 j2 jr i1 i2 ir ir+1 . . . Greedy: OPT: jr+1 job ir+1 finishes after jr+1 Greedy will select job jr+1 before job ir+1.
  • 19. Interval Partitioning  Interval scheduling so far is using a single resource.  Extension: What if we have multiple resources for scheduling tasks?  Assumption: all resources are equivalent
  • 20. Interval Partitioning  Interval partitioning. » Lecture j starts at sj and finishes at fj. » Goal: find minimum number of classrooms to schedule all lectures so that no two lectures occur at the same time in the same room.  Ex: This schedule uses 4 classrooms to schedule 10 lectures. Time 9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30 h c b a e d g f i j 3 3:30 4 4:30 1 2 3 4
  • 21. Interval Partitioning  Interval partitioning. » Lecture j starts at sj and finishes at fj. » Goal: find minimum number of classrooms to schedule all lectures so that no two occur at the same time in the same room.  Ex: This schedule uses only 3. Time 9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30 h c a e f g i j 3 3:30 4 4:30 d b 1 2 3
  • 22. Interval Partitioning: Lower Bound on Optimal Solution  Def. The depth of a set of open intervals is the maximum number that contain all concurrent intervals at any given time.  Key observation. Number of classrooms needed  depth.  Ex: Depth of schedule below = 3  schedule below is optimal.  Q. Does there always exist a schedule equal to depth of intervals? Time 9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30 h c a e f g i j 3 3:30 4 4:30 d b a, b, c all contain 9:30 1 2 3
  • 23. 23 Interval Partitioning: Lower Bound on Optimal Solution  Def. The depth of a set of open intervals is the maximum number that contain all concurrent intervals at any given time.  Key observation. Number of classrooms needed  depth.  Ex: Depth of schedule below = 3  schedule below is optimal.  Q. Does there always exist a schedule equal to Time 9 9:30 10 10:30 11 11:30 12 12:30 1 1:30 2 2:30 h c a e f g i j 3 3:30 4 4:30 d b a, b, c all contain 9:30 1 2 3
  • 24. 24 Interval Partitioning: Greedy Algorithm  Greedy algorithm. Consider lectures in increasing order of start time: assign lecture to any compatible classroom.  Implementation. O(n log n). Sort intervals by starting time so that s1  s2  ...  sn. d  0 for j = 1 to n { if (lecture j is compatible with some classroom k) schedule lecture j in classroom k else allocate a new classroom d + 1 schedule lecture j in classroom d + 1 d  d + 1 } number of allocated classrooms
  • 25. 25 Interval Partitioning: Greedy Analysis  Observation. Greedy algorithm never schedules two incompatible lectures in the same classroom.  Theorem. Greedy algorithm is optimal.  Pf. » Let d = number of classrooms that the greedy algorithm allocates. » Classroom d is opened because we needed to schedule a job, say j, that is incompatible with all d-1 other classrooms. » These d-1 jobs each end after sj (because of incompatible). » Since we sorted by start time, all these incompatibilities
  • 26. 4.2 Scheduling to Minimize Lateness What if all jobs do not have predefined fixed starting time? Use a single resource to complete all jobs one after another
  • 27. 27 Scheduling to Minimizing Lateness  Minimizing lateness problem. » Single resource processes one job at a time. » Job j requires tj units of processing time and is due at time dj. » If j starts at time sj, it finishes at time fj = sj + tj. » Lateness: j = max { 0, fj - dj }. » Goal: schedule all jobs to minimize maximum lateness L = max j.  Ex: dj 6 tj 3 1 8 2 2 9 1 3 9 4 4 14 3 5 15 2 6 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 d5 = 14 d2 = 8 d6 = 15 d1 = 6 d4 = 9 d3 = 9 lateness = 0 lateness = 2 max lateness = 6
  • 28. 28 Minimizing Lateness: Greedy Algorithms  Greedy template. Consider jobs in some order. » [Shortest processing time first] Consider jobs in ascending order of processing time tj. » [Earliest deadline first] Consider jobs in ascending order of deadline dj. » [Smallest slack] Consider jobs in ascending order of slack dj - tj.
  • 29. 29  Greedy template. Consider jobs in some order. » [Shortest processing time first] Consider jobs in ascending order of processing time tj. » [Smallest slack] Consider jobs in ascending order of slack dj - tj. counterexample counterexample dj tj 100 1 1 10 10 2 dj tj 2 1 1 10 10 2 Minimizing Lateness: Greedy Algorithms
  • 30. 30 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 d5 = 14 d2 = 8 d6 = 15 d1 = 6 d4 = 9 d3 = 9 max lateness = 1 Sort n jobs by deadline so that d1  d2  …  dn t  0 for j = 1 to n Assign job j to interval [t, t + tj] sj  t, fj  t + tj t  t + tj output intervals [sj, fj] Minimizing Lateness: Greedy Algorithm  Greedy algorithm. Earliest deadline first. dj 6 tj 3 1 8 2 2 9 1 3 9 4 4 14 3 5 15 2 6
  • 31. 31 Minimizing Lateness: No Idle Time  Observation. There exists an optimal schedule with no idle time.  Observation. The greedy schedule has no idle time. 0 1 2 3 4 5 6 d = 4 d = 6 7 8 9 10 11 d = 12 0 1 2 3 4 5 6 d = 4 d = 6 7 8 9 10 11 d = 12
  • 32. 32 Minimizing Lateness: Inversions  Def. Given a schedule S, an inversion is a pair of jobs i and j such that: di < dj but j scheduled before i.  Observation. Greedy schedule has no inversions and no idle time. i j before swap fi inversion [ as before, we assume jobs are numbered so that d1  d2  …  dn ]
  • 33. 33 Minimizing Lateness: Inversions  Def. Given a schedule S, an inversion is a pair of jobs i and j such that: i < j but j scheduled before i.  Claim. Swapping two consecutive, inverted jobs reduces the number of inversions by one and does not increase the max lateness.  Pf. Let  be the lateness before the swap, and let  ' be it afterwards. »  'k = k for all k  i, j   j   fj  dj (definition)  fi  dj ( j finishes at time fi )  fi  di (i  j)  i (definition) i j i j before swap after swap f'j fi inversion
  • 34. 34 Claim. All schedules with no inversion and no idle time have the same maximum lateness. Pf. Two such schedules must differ in the order in which jobs with identical deadlines are scheduled. Jobs with this same deadline are scheduled consecutively. The last of these jobs have the largest lateness, not depend on the order of these jobs.
  • 35. 35 Minimizing Lateness: Analysis of Greedy Algorithm  Theorem. Greedy schedule S is optimal.  Pf. Define S* to be an optimal schedule that has the fewest number of inversions, and let's see what happens. » Can assume S* has no idle time. » If S* has no inversions, then S = S* (greedy schedule result S is also with no inversions and idle time) » If S* has an inversion, let i-j be an adjacent inversion. • swapping i and j does not increase the maximum lateness and strictly decreases the number of inversions • this contradicts definition of S* ▪
  • 36. 36 Greedy Analysis Strategies  Greedy algorithm stays ahead. Show that after each step of the greedy algorithm, its solution is at least as good as any other algorithm's.  Structural. Discover a simple "structural" bound asserting that every possible solution must have a certain value. Then show that your algorithm always achieves this bound.  Exchange argument. Gradually transform any solution to the one found by the greedy algorithm without hurting its quality.

Editor's Notes

  1. 2
  2. 3
  3. 4
  4. 5
  5. 6
  6. 7
  7. Activity selection = interval scheduling OPT = B, E, H Note: smallest job (C) is not in any optimal solution, job that starts first (A) is not in any optimal solution.
  8. priority queue keyed by the finish time of the last job added
  9. Note: finding a maximal size subset of jobs that meet deadline is NP-hard.
  10. "machine not working for some reason, yet work still to be done"
  11. Recall: jobs sorted in ascending order of due dates
  12. fi - di <= max {0, fi - di} = li
  13. Hard, if not impossible, to precisely define "greedy algorithm." Though there are some formalizations, e.g., matroids. myopic greedy: "at every iteration, the algorithm chooses the best morsel it can swallow, without worrying about the future" Objective function. Does not explicitly appear in greedy algorithm!