Tải bản đầy đủ - 0 (trang)
2 Dijkstra's Algorithm for Single-Source Shortest Paths

2 Dijkstra's Algorithm for Single-Source Shortest Paths

Tải bản đầy đủ - 0trang

addthenewvertexvtoY;

addtheedge(ontheshortestpath)thattouchesvto



if(Y==V)

theinstanceissolved;//solutionchec

}

Figure4.8illustratesDijkstra'salgorithm.AswasthecaseforPrim's

algorithm,thehigh-levelalgorithmworksonlyforahumansolvingan

instancebyinspectiononasmallgraph.Nextwegiveadetailed

algorithm.Forthisalgorithm,theweightedgraphisrepresentedbyatwodimensionalarrayexactlyaswasdoneinSection3.2.Thisalgorithmis

verysimilartoAlgorithm4.1(Prim's).Thedifferenceisthatinsteadofthe

arraysnearestanddistance,wehavearraystouchandlength,wherefor

i=2,…,n,





Figure4.8:Aweighted,directedgraph(inupper-leftcorner)andthe

stepsinDijkstra'salgorithmforthatgraph.TheverticesinYandthe

edgesinFareshadedincolorateachstep.

touch[i]=indexofvertexvinYsuchthattheedgeisthelastedge

onthecurrentshortestpathfromv1toviusingonlyverticesinYas

intermediates.



length[i]=lengthofthecurrentshortestpathfromv1toviusingonly

verticesinYasintermediates.

Thealgorithmfollows.

Algorithm4.3:Dijkstra'sAlgorithm

Problem:Determinetheshortestpathsfromv1toallotherverticesina

weighted,directedgraph.

Inputs:integern≥2,andaconnected,weighted,directedgraph

containingnvertices.Thegraphisrepresentedbyatwo-dimensional

arrayW,whichhasbothitsrowsandcolumnsindexedfrom1ton,where

W[i][j]istheweightontheedgefromtheithvertextothejthvertex.

Outputs:setofedgesFcontainingedgesinshortestpaths.

voiddijkstra(intn,

constnumberW[][],

set_of_edges&F)

{

indexi,unear;

edgee;

indextouch[2..n];

numberlength[2..n];



F=Ø;

for(i=2;i<=n;i++){//Forallve

touch[i]=1;//tobeth

length[i]=W[1][i];//currentsh

}//v1,

//thatpath

//ontheedg

repeat(n-1times){//Addall

min=∞;

for(i=2;i<=n;i++)//Checkeach

if(0≤length[i]


min=length[i];

unear=i;

}

e=edgefromvertexindexedbytouch[vnear]

tovertexindexedbyvnear;

addetoF;

for(i=2;i<=n;i++)

if(length[vnear]+W[vnear][i]
length[i]=length[vnear]+W[vnear][i]

touch[i]=vnear;//Foreach

}//updateit

length[vnear]=-1;//

}//to

}



Becauseweareassumingthatthereisapathfromv1toeveryother

vertex,thevariablevnearhasanewvalueineachiterationofthe

repeatloop.Ifthiswerenotthecase,thealgorithm,aswritten,would

endupaddingthelastedgeoverandoveruntiln-1iterationsofthe

repeatloopwerecompleted.

Algorithm4.3determinesonlytheedgesintheshortestpaths.Itdoesnot

producethelengthsofthosepaths.Theselengthscouldbeobtained

fromtheedges.Alternatively,asimplemodificationofthealgorithm

wouldenableittocomputethelengthsandstoretheminanarrayas

well.

ThecontrolinAlgorithm4.3isidenticaltothatinAlgorithm4.1.

Therefore,fromtheanalysisofthatAlgorithm4.1,weknowforAlgorithm

4.3that



Althoughwedonotdoithere,itispossibletoprovethatAlgorithm4.3

alwaysproducesshortestpaths.Theproofusesaninductionargument

similartotheoneusedtoprovethatPrim'salgorithm(Algorithm4.1)



alwaysproducesaminimumspanningtree.

AsisthecaseforPrim'salgorithm,Dijkstra'salgorithmcanbe

implementedusingaheaporaFibonacciheap.Theheap

implementationisθ(mlgn),andtheFibonacciheapimplementationis

θ(m+nlgn),wheremisthenumberofedges.SeeFredmanandTarjan

(1987)forthislatterimplementation.



4.3Scheduling

Supposeahairstylisthasseveralcustomerswaitingfordifferent

treatments(e.g.,simplecut,cutwithshampoo,permanent,haircoloring).

Thetreatmentsdon'talltakethesameamountoftime,butthestylist

knowshowlongeachtakes.Aresonablegoalwouldbetoschedulethe

customersinsuchawayastominimizethetotaltimetheyspendboth

waitingandbeingserved(gettingtreated).Suchascheduleisconsidered

optimal.Thetimespentbothwaitingandbeingservediscalledthetime

inthesystem.Theproblemofminimizingthetotaltimeinthesystem

hasmanyapplications.Forexample,wemaywanttoscheduleusers'

accesstoadiskdrivetominimizethetotaltimetheyspendwaitingand

beingserved.

Anotherschedulingproblemoccurswheneachjob(customer)takesthe

sameamountoftimetocompletebuthasadeadlinebywhichitmust

starttoyieldaprofitassociatedwiththejob.Thegoalistoschedulethe

jobstomaximizethetotalprofit.Wewillconsiderschedulingwith

deadlinesafterdiscussingthesimplerschedulingproblemofminimizing

thetotaltimeinthesystem.



4.3.1MinimizingTotalTimeintheSystem

Asimplesolutiontominimizingthetotaltimeinthesystemistoconsider

allpossibleschedulesandtaketheminimum.Thisisillustratedinthe

followingexample.

Example4.2

Supposetherearethreejobsandtheservicetimesforthesejobsare



Theactualtimeunitsarenotrelevanttotheproblem.Ifweschedule

themintheorder1,2,3,thetimesspentinthesystemforthethreejobs

areasfollows:



Job TimeintheSystem

1



5(servicetime)



2



5(waitforjob1)+10(servicetime)



3



5(waitforjob1)+10(waitforjob2)+4(servicetime)



Thetotaltimeinthesystemforthisscheduleis



Thissamemethodofcomputationyieldsthefollowinglistofallpossible

schedulesandtotaltimesinthesystem:

Schedule TotalTimeintheSystem

[1,2,3] 5+(5+10)+(5+10+4)=39

[1,3,2] 5+(5+4)+(5+4+10)=33

[2,1,3] 10+(10+5)+(10+5+4)=44

[2,3,1] 10+(10+4)+(10+4+5)=43

[3,1,2] 4+(4+5)+(4+5+10)=32

[3,2,1] 4+(4+10)+(4+10+5)=37

Schedule[3,1,2]isoptimalwithatotaltimeof32.



Clearly,analgorithmthatconsidersallpossibleschedulesisfactorialtime.Noticeinthepreviousexamplethatanoptimalscheduleoccurs

whenthejobwiththesmallestservicetime(job3,withaservicetimeof

4)isscheduledfirst,followedbythejobwiththesecond-smallestservice

time(job1,withaservicetimeof5),followedfinallybythejobwiththe

largestservicetime(job2,withaservicetimeof10).Intuitively,itseems

thatsuchaschedulewouldbeoptimalbecauseitgetstheshortestjobs

outofthewayfirst.Ahigh-levelgreedyalgorithmforthisapporachisas

follows:



sortthejobsbyservicetimeinnondecreasingorder;



while(theinstanceisnotsolved){

schedulethenextjob;//selectionprocedureand

//feasibilitycheck

if(therearenomorejobs)//solutioncheck

theinstanceissolved;

}

Wewrotethisalgorithminthegeneralformofthegreedyapproachto

showthatitisindeedagreedyalgorithm.However,clearlyallthe

algorithmdoesissortthejobsaccordingtoservicetime.Itstime

complexityisthereforegivenby



Althoughintuitivelyitseemsthattheschedulecreatedbythisalgorithmis

optimal,thissuppositionneedstobeproved.Thefollowingtheorem

provesthestrongerresultthatthisscheduleistheonlyoptimalone.

Theorem4.3

Theonlyschedulethatminimizesthetotaltimeinthesystemisonethat

schedulesjobsinnondecreasingorderbyservicetime.

Proof:For1≤i≤n−1,lettibetheservicetimefortheithjobscheduled

insomeparticularoptimalschedule(onethatminimizesthetotaltimein

thesystem).Weneedtoshowthattheschedulehasthejobsscheduled

innondecreasingorderbyservicetime.Weshowthisusingproofby

contradiction.Iftheyarenotscheduledinnondecreasingorder,thenfor

atleastoneiwhere1≤i≤n−1,



Wecanrearrangeouroriginalschedulebyinterchangingtheithand

(i+1)stjobs.Bydoingthis,wehavetakentiunitsoffthetimethe(i+1)st

job(intheoriginalschedule)spendsinthesystem.Thereasonisthatit



nolongerwaitswhiletheithjob(intheoriginalschedule)isbeingserved.

Similarly,wehaveaddedti+1unitstothetimetheithjob(intheorignal

schedule)spendsinthesystem.Clearly,wehavenotchangedthetime

thatanyotherjobspendsinthesystem.Therefore,ifTisthetotaltimein

thesysteminouroriginalscheduleandT'isthetotaltimeinthe

rearrangedschedule,



Becauseti>ti+1,



whichcontradictstheoptimalityofouroriginalschedule.



ItisstraightforwardtogeneralizeouralgorithmtohandletheMultipleServerSchedulingproblem.Supposetherearemservers.Orderthose

serversinanarbitrarymanner.Orderthejobsagainbyservicetimein

nondecreasingorder.Letthefirstserverservethefirstjob,thesecond

serverthesecondjob,…,andthemthserverthemthjob.Thefirstserver

willfinishfirstbecausethatserverservesthejobwiththeshortestservice

time.Therefore,thefirstserverservesthe(m+1)stjob.Similarly,the

secondserverservesthe(m+2)ndjob,andsoon.Theschemeisas

follows:



Clearly,thejobsendupbeingprocessedinthefollowingorder:



Thatis,thejobsareprocessedinnondecreasingorderbyservicetime.



4.3.2SchedulingwithDeadlines

Inthisschedulingproblem,eachjobtakesoneunitoftimetofinishand

hasadeadlineandaprofit.Ifthejobstartsbeforeoratitsdeadline,the

profitisobtained.Thegoalistoschedulethejobssoastomaximizethe

totalprofit.Notalljobshavetobescheduled.Weneednotconsiderany

schedulethathasajobscheduledafteritsdeadlinebecausethat

schedulehasthesameprofitasonethatdoesn'tschedulethejobatall.

Wecallsuchascheduleimpossible.Thefollowingexampleillustrates

thisproblem.

Example4.3

Supposewehavethefollowingjobs,deadlines,andprofits:

Job Deadline Profit

1



2



30



2



1



35



3



2



25



4



1



40



Whenwesaythatjob1hasadeadlineof2,wemeanthatjob1canstart

attime1ortime2.Thereisnotime0.Becausejob2hasadeadlineof1,

thatjobcanstartonlyattime1.Thepossibleschedulesandtotalprofits

areasfollows:

Schedule TotalProfit

[1,3] 30+25=55

[2,1] 35+30=65

[2,3] 35+25=60

[3,1] 25+30=55

[4,1] 40+30=70

[4,3] 40+25=65

Impossiblescheduleshavenotbeenlisted.Forexample,schedule[1,2]



isnotpossible,andisthereforenotlisted,becausejobIwouldstartfirst

attime1andtakeoneunitoftimetofinish,causingjob2tostartattime

2.However,thedeadlineforjob2istime1.Schedule[1,3],forexample,

ispossiblebecausejob1isstartedbeforeitsdeadline,andjob3is

startedatitsdeadline.Weseethatschedule[4,1]isoptimalwithatotal

profitof70.



Toconsiderallschedules,asisdoneinExample4.3,takesfactorialtime.

Noticeintheexamplethatthejobwiththegreatestprofit(job4)is

includedintheoptimalschedule,butthejobwiththesecond-greatest

profit(job2)isnot.Becausebothjobshavedeadlinesequalto1,both

cannotbescheduled.Ofcourse,theonewiththegreatestprofitisthe

onescheduled.Theotherjobscheduledisjob1,becauseitsprofitis

greaterthanthatofjob3.Thissuggeststhatareasonablegreedy

approachtosolvingtheproblemwouldbetofirstsortthejobsin

nonincreasingorderbyprofit,andnextinspecteachjobinsequenceand

addittothescheduleifitispossible.Beforewecancreateevenahighlevelalgorithmforthisapproach,weneedsomedefinitions.

Asequenceiscalledafeasiblesequenceifallthejobsinthesequence

startbytheirdeadlines.Forexample,[4,1]isafeasiblesequencein

Example4.3,but[1,4]isnotafeasiblesequence.Asetofjobsiscalleda

feasiblesetifthereexistsatleastonefeasiblesequenceforthejobsin

theset.InExample4.3,{1,4}isafeasiblesetbecausethescheduling

sequence[4,1]isfeasible,whereas{2,4}isnotafeasiblesetbecauseno

schedulingsequenceallowsbothjobstostartbytheirdeadlines.Our

goalistofindafeasiblesequencewithmaximumtotalprofit.Wecall

suchasequenceanoptimalsequenceandthesetofjobsinthe

sequenceanoptimalsetofjobs.Wecannowpresenthigh-levelgreedy

algorithmfortheSchedulingwithDeadlinesproblem.

sortthejobsinnonincreasingorderbyprofit;

S=Ø

while(theinstanceisnotsolved){



selectnextjob;//selectionproce



if(Sisfeasiblewiththisjobadded)//feasibilitychec

addthisjobtoS;

if(therearenomorejobs)//solutioncheck

theinstanceissolved;

}

Thefollowingexampleillustratesthisalgorithm.

Example4.4

Supposewehavethefollowingjobs,deadlines,andprofits:

Job Deadline Profit

1



3



40



2



1



35



3



1



30



4



3



25



5



1



20



6



3



15



7



2



10



Wehavealreadysortedthejobsbeforelabelingthem.Theprevious

greedyalgorithmdoesthefollowing:

1. SissettoØ.

2. Sissetto{1}becausethesequence[1]isfeasible.

3. Sissetto{1,2}becausethesequence[2,1]isfeasible.

4. {1,2,3}isrejectedbecausethereisnofeasiblesequencefor

thisset.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

2 Dijkstra's Algorithm for Single-Source Shortest Paths

Tải bản đầy đủ ngay(0 tr)

×