




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
GreedyAlgorithms(I)Greed,forlackofabetterword,isgood!Greedisright!Greedworks!-MichaelDouglas,U.S.actorintheroleofGordonGecko,inthefilmWallStreet,1987GreedyAlgorithms(I)Greed,foMaintopicsIdeaofthegreedyapproachChange-makingproblemMinimumspanningtreeproblemPrim’salgorithmKruskal’salgorithmPropertiesofminimumspanningtree(additivepart)Bottleneckspanningtree(additivepart)MaintopicsIdeaofthegreedyExpectedOutcomesStudentshouldbeabletosummarizetheideaofthegreedytechniquelistseveralapplicationsofthegreedytechniqueapplythegreedytechniquetochange-makingproblemdefinetheminimumspanningtreeproblemdescribeideasofPrimandKruskal’salgorithmsforcomputingminimumspanningtreeprovethecorrectnessofthetwoalgorithmsanalyzethetimecomplexitiesofthetwoalgorithmsunderdifferentdatastructuresprovethevariouspropertiesofminimumspanningtreeExpectedOutcomesStudentshoulGlossaryGreedy:贪婪的Change-makingproblem:找零钱问题Cashier:收银员Denomination:货币单位,面额Quarter,dime,nickel,penny:2角5分,1角,5分,1分(美国硬币单位)Irrevocable:不可取消的,不可逆的Spanningtree:生成树,支撑树GlossaryGreedy:贪婪的AnticipatorySet:
ChangeMakingProblemHowtomake48centsofchangeusingcoinsofdenominationsof25(1quartercoin),10(1dimecoin),5(1nickelcoin),and1(1pennycoin)sothatthetotalnumberofcoinsisthesmallest?Theidea:Takethecoinwithlargestdenominationwithoutexceedingtheremainingamountofcents,makethelocallybestchoiceateachstep.Isthesolutionoptimal?Yes,theproofisleftasexercise.AnticipatorySet:
ChangeMakiGeneralChange-MakingProblemGivenunlimitedamountsofcoinsofdenominationsd1>…>dm,givechangeforamountnwiththeleastnumberofcoins.Doesthegreedyalgorithmalwaysgiveanoptimalsolutionforthegeneralchange-makingproblem?Wegivethefollowingexample,Example:d1=7c,d2=5c,d3=1c,andn=10c,notalwaysproducesanoptimalsolution.infact,forsomeinstances,theproblemmaynothaveasolutionatall!considerinstanced1=7c,d2=5c,d3=3c,andn=11c.But,thisproblemcanbesolvedbydynamicprogramming,pleasetrytodesignanalgorithmforthegeneralchange-makingproblemafterclass.GeneralChange-MakingProblemGGreedyAlgorithmsAgreedyalgorithmmakesalocallyoptimalchoicestepbystepinthehopethatthischoicewillleadtoagloballyoptimalsolution.
Thechoicemadeateachstepmustbe:FeasibleSatisfytheproblem’sconstraintslocallyoptimalBethebestlocalchoiceamongallfeasiblechoicesIrrevocableOncemade,thechoicecan’tbechangedonsubsequentsteps.Dogreedyalgorithmsalwaysyieldoptimalsolutions?Example:changemakingproblemwithadenominationsetof7,5and1,andn=10?GreedyAlgorithmsAgreedyalgoApplicationsoftheGreedyStrategyOptimalsolutions:someinstancesofchangemakingMinimumSpanningTree(MST)Single-sourceshortestpathsHuffmancodesApproximations:TravelingSalesmanProblem(TSP)KnapsackproblemotheroptimizationproblemsForsomeproblems,yieldsanoptimalsolutionforeveryinstance.Formost,doesnotbutcanbeusefulforfastapproximations.ApplicationsoftheGreedyStrMinimumSpanningTree(MST)SpanningtreeofaconnectedgraphGisaconnectedacyclicsubgraph(tree)ofGthatincludesallofG’svertices.Note:aspanningtreewithnverticeshasexactlyn-1edges.MinimumSpanningTreeofaweighted,connectedgraphGisaspanningtreeofGofminimumtotalweight.Example:MinimumSpanningTree(MST)SpaMSTProblemGivenaconnected,undirected,weightedgraphG=(V,E),findaminimumspanningtreeforit.ComputeMSTthroughBruteForce?Kruskal:1956,Prim:1957BruteforceGenerateallpossiblespanningtreesforthegivengraph.Findtheonewithminimumtotalweight.FeasibilityofBruteforcePossibletoomanytrees(exponentialfordensegraphs)MSTProblemGivenaconnected,ThePrim’sAlgorithmIdeaofthePrim’salgorithmPseudo-codeofthealgorithmCorrectnessofthealgorithm(important)TimecomplexityofthealgorithmThePrim’sAlgorithmIdeaofthIdeaofPrimGrowasingletreebyrepeatedlyaddingtheleastcostedge(greedystep)thatconnectsavertexintheexistingtreetoavertexnotintheexistingtreeIntermediatesolutionisalwaysasubtreeofsomeminimumspanningtree.IdeaofPrimGrowasingletreePrim’sMSTalgorithmStartwithatree,T0,consistingofonevertex“Grow”treeonevertex/edgeatatimeConstructaseriesofexpandingsubtreesT1,T2,…Tn-1..AteachstageconstructTifromTi-1byaddingtheminimumweightedgethatconnectingavertexintree(Ti-1)toavertexnotyetinthetreethisisthe“greedy”step!AlgorithmstopswhenallverticesareincludedPrim’sMSTalgorithmStartwithPseudocodeofthePrimALGORITHMPrim(G)//Prim’salgorithmforconstructingaminimumspanningtree//Input:AweightedconnectedgraphG=(V,E)//Output:ET,thesetofedgescomposingaminimumspanningtreeofGVT{v0}//v0canbearbitrarilyselectedETfor
i1to|V|-1dofindaminimum-weightedgee*=(v*,u*)amongalltheedges(v,u)suchthatvisinVTanduisinV-VT
VTVT{u*}
ETET{e*}return
ETPseudocodeofthePrimALGORITHAnexampleaedcb1524637Anexampleaedcb1524637ThePrim’salgorithmisgreedy!Thechoiceofedgesaddedtocurrentsubtreesatisfyingthethreepropertiesofgreedyalgorithms.Feasible,eachedgeaddedtothetreedoesnotresultinacycle,guaranteethatthefinalETisaspanningtreeLocaloptimal,eachedgeselectedtothetreeisalwaystheonewithminimumweightamongalltheedgescrossingVTandV-VTIrrevocable,onceanedgeisaddedtothetree,itisnotremovedinsubsequentsteps.ThePrim’salgorithmisgreedyCorrectnessofPrimProvebyinductionthatthisconstructionprocessactuallyyieldsMST.T0isasubsetofallMSTsSupposethatTi-1isasubsetofsomeMSTT,weshouldprovethatTiwhichisgeneratedfromTi-1isalsoasubsetofsomeMST.Bycontradiction,assumethatTidoesnotbelongtoanyMST.Letei=(u,v)betheminimumweightedgefromavertexinTi-1toavertexnotinTi-1usedbyPrim’salgorithmtoexpandingTi-1toTi,accordingtoourassumption,eicannotbelongtoMSTT.AddingeitoTresultsinacyclecontaininganotheredgee’=(u’,v’)connectingavertexu’inTi-1toavertexv’notinit,andw(e’)w(ei)accordingtothegreedyPrim’salgorithm.Removinge’fromTandaddingeitoTresultsinanotherspanningtreeT’withweightw(T’)w(T),indicatingthatT’isaminimumspanningtreeincludingTiwhichcontradicttoassumptionthatTidoesnotbelongtoanyMST.CorrectnessofPrimProvebyinCorrectnessofPrimCorrectnessofPrimImplementationofPrimHowtoimplementthestepsinthePrim’salgorithm?Firstidea,labeleachvertexwitheither0or1,1representsthevertexinVT,and0otherwise.Traversetheedgesettofindanminimumweightedgewhoseendpointshavedifferentlabels.Timecomplexity:O(VE)ifadjacencylinkedlistandO(V3)foradjacencymatrixForsparsegraphs,useadjacencylinkedlistAnyimprovement?ImplementationofPrimHowtoiNotationsT:theexpandingsubtree.Q:theremainingvertices.Ateachstage,thekeypointofexpandingthecurrentsubtreeTistoDeterminewhichvertexinQisthenearestvertextoT.Qcanbethoughtofasapriorityqueue:Thekey(priority)ofeachvertex,key[v],meanstheminimumweightedgefromvtoavertexinT.Key[v]is∞ifvisnotlinkedtoanyvertexinT.Themajoroperationistotofindanddeletethenearestvertex(v,forwhichkey[v]isthesmallestamongallthevertices)RemovethenearestvertexvfromQandadditandthecorrespondingedgetoT.Withtheoccurrenceofthataction,thekeyofv’sneighborswillbechanged.ToremembertheedgesoftheMST,anarray[]isintroducedtorecordtheparentofeachvertex.Thatis[v]isthevertexintheexpandingsubtreeTthatisclosesttovnotinT.NotationsT:theexpandingsubtAdvancedPrim’sAlgorithmALGORITHMMST-PRIM(G,w,r)//w:weight;r:root,thestartingvertexforeachu
V[G]
do
key[u]
[u]NIL
//[u]:theparentofukey[r]0QV[G] //Nowthepriorityqueue,Q,hasbeenbuilt.while
Q
douExtract-Min(Q)//removethenearestvertexfromQ
foreachvAdj[u]//updatethekeyforeachofv’sadjacentnodes.
do
if
vQandw(u,v)<key[v]
then
[v]ukey[v]w(u,v)AdvancedPrim’sAlgorithmALGO国外算法设计与分析课件2TimeComplexityofPrim’salgorithmNeedpriorityqueueforlocatingthenearestvertexUseunorderedarraytostorethepriorityqueue: Efficiency:Θ(n2)Usebinarymin-heaptostorethepriorityqueue Efficiency:Forgraphwithnverticesandmedges:
O(mlogn)UseFibonacci-heaptostorethepriorityqueue:Efficiency:Forgraphwithnverticesandmedges:
O(nlogn+m)TimeComplexityofPrim’salgoKruskal’sMSTAlgorithmEdgesareinitiallysortedbyincreasingweightStartwithanemptyforestF0“grow”MSToneedgeatatimethroughaseriesofexpandingforestsF1,F2,…,Fn-1intermediatestagesusuallyhaveforestoftrees(notconnected)ateachstageaddminimumweightedgeamongthosenotyetusedthatdoesnotcreateacycleneedefficientwayofdetecting/avoidingcyclesalgorithmstopswhenallverticesareincludedKruskal’sMSTAlgorithmEdgesaCorrectnessofKruskalSimilartotheproofofPrimProvebyinductionontheconstructionprocessactuallygenerateaMSTConsiderF0,F1,…,Fn-1CorrectnessofKruskalSimilarBasicKruskal’sAlgorithmALGORITHMKruscal(G)//Input:AweightedconnectedgraphG=<V,E>
//Output:ET,thesetofedgescomposingaminimumspanningtreeofG.SortEinnondecreasingorderoftheedgeweightsw(ei1)<=…<=w(ei|E|) ET
;ecounter
0
//initializethesetoftreeedgesanditssizek0
whileencounter<|V|-1
do kk+1
ifET
U{eik}isacyclic
ET
ETU{eik};ecounterecounter+1returnETBasicKruskal’sAlgorithmALGORKruskal’sAlgorithm(AdvancedPart)Kruskal’sAlgorithm(Advanced国外算法设计与分析课件2Kruskal:TimeComplexity
O(EV)whendisjoint-setdatastructurearenotused.Whenusedisjoint-setdatastructurewithunion-by-rankandpath-compressionheuristics:InitializingthesetAinline1takesO(1)time.
O(V)MAKE-SEToperationsinlines2-3Sorttheedgesinline4takesO(ElogE)time.Theforloopoflines5-8performsO(E)FIND-SETandUNIONoperationsonthedisjoint-setforestb)andd)takeatotalofO((V+E)(V))Line9:O(V+E)Notethat:E
V-1and(V)=O(logV)=O(logE)andEV2SOtotaltimeis:O(ElogV)Kruskal:TimeComplexityO(EV)PropertiesofMSTProperty1:Let(u,v)beaminimum-weightedgeinagraphG=(V,E),then(u,v)belongstosomeminimumspanningtreeofG.Proofhint:suppose(u,v)isnotinMSTT,constructanotherMSTT’including(u,v).PropertiesofMSTProperty1:PropertiesofMSTProperty2Agraphhasauniqueminimumspanningtreeifalltheedgeweightsarepairwisedistinct.Theconversedoesnothold.PropertiesofMSTProperty2PropertiesofMSTProperty3LetTbeaminimumspanningtreeofagraphG,andletT’beanarbitraryspanningtreeofG,supposetheedgesofeachtreearesortedinnon-decreasingorder,thatis,w(e1)w(e2)…w(en-1)andw(e1’)w(e2’)…w(en-1’),thenfor1in-1,w(ei)w(ei’).Property4LetTbeaminimumspanningtreeofagraphG,andletLbethesortedlistoftheedgeweightsofT,thenforanyotherminimumspanningtreeT’ofG,thelistLisalsothesortedlistofedgeweightsofT’.PropertiesofMSTProperty3PropertiesofMSTProperty5Lete=(u,v)beamaximum-weightedgeonsomecycleofG.Provethatthereisaminimumspanningtreethatdoesnotincludee.Proof.ArbitrarilychooseaMSTT.IfTdoesnotcontaine,itisproved.Otherwise,T\eisdisconnected,andsupposeX,YarethetwoconnectedcomponentsofT\e.LeteisoncycleCinG.LetP=C\e.Thenthereisanedge(x,y)onPsuchthatxX,andy
Y.Andw(x,y)w(e).T’=T\e+(x,y)isaspanningtreeandw(T’)w(T).Alsowehavew(T)w(T’),sow(T’)=w(T).T’isaMSTnotincludinge.PropertiesofMSTProperty5BottleneckSpanningTreeAbottleneckspanningtree
Tofaconnected,weightedandundirectedgraphGisaspanningtreeofGwhoselargestedgeweightisminimumoverallspanningtreesofG.LetT1,T2,…,TmareallthespanningtreesofG,andthelargestedgeofeachtreeiset1,et2,…,etm,supposew(eti)w(etj)for1jmandji,thenTi
is
abottleneckspanningtree.ThevalueofaBSTTistheweightofthemaximum-weightedgeinT.Thebottleneckspanningtreemaynotbeunique.BottleneckSpanningTreeAbottBSTvsMSTEveryminimumspanningtreeisabottleneckspanningtree.Property4impliesit.Aneasierproof:LetTbeaMSTandT’beaBST,letthemaximum-weightedgeinTandT’beeande’,respectively.SupposeforthecontrarythattheMSTTisnotaBST,thenwehavew(e)>w(e’),whichalsoindicatesthattheweightofeisgreaterthanthatofanyedgesinT’.RemovingefromTdisconnectsTintotwosubtreesT1andT2,theremustexistanedgefinT’connectingT1andT2,otherwise,Tisnotconnected.T1T2{f}formsanewtreeT’’withw(T’’)=w(T)-w(e)+w(f)<
w(T),AcontradictiontothefactthatTisMST,thus,AMSTisalsoaBST.BSTvsMSTEveryminimumspanniGreedyAlgorithms(I)Greed,forlackofabetterword,isgood!Greedisright!Greedworks!-MichaelDouglas,U.S.actorintheroleofGordonGecko,inthefilmWallStreet,1987GreedyAlgorithms(I)Greed,foMaintopicsIdeaofthegreedyapproachChange-makingproblemMinimumspanningtreeproblemPrim’salgorithmKruskal’salgorithmPropertiesofminimumspanningtree(additivepart)Bottleneckspanningtree(additivepart)MaintopicsIdeaofthegreedyExpectedOutcomesStudentshouldbeabletosummarizetheideaofthegreedytechniquelistseveralapplicationsofthegreedytechniqueapplythegreedytechniquetochange-makingproblemdefinetheminimumspanningtreeproblemdescribeideasofPrimandKruskal’salgorithmsforcomputingminimumspanningtreeprovethecorrectnessofthetwoalgorithmsanalyzethetimecomplexitiesofthetwoalgorithmsunderdifferentdatastructuresprovethevariouspropertiesofminimumspanningtreeExpectedOutcomesStudentshoulGlossaryGreedy:贪婪的Change-makingproblem:找零钱问题Cashier:收银员Denomination:货币单位,面额Quarter,dime,nickel,penny:2角5分,1角,5分,1分(美国硬币单位)Irrevocable:不可取消的,不可逆的Spanningtree:生成树,支撑树GlossaryGreedy:贪婪的AnticipatorySet:
ChangeMakingProblemHowtomake48centsofchangeusingcoinsofdenominationsof25(1quartercoin),10(1dimecoin),5(1nickelcoin),and1(1pennycoin)sothatthetotalnumberofcoinsisthesmallest?Theidea:Takethecoinwithlargestdenominationwithoutexceedingtheremainingamountofcents,makethelocallybestchoiceateachstep.Isthesolutionoptimal?Yes,theproofisleftasexercise.AnticipatorySet:
ChangeMakiGeneralChange-MakingProblemGivenunlimitedamountsofcoinsofdenominationsd1>…>dm,givechangeforamountnwiththeleastnumberofcoins.Doesthegreedyalgorithmalwaysgiveanoptimalsolutionforthegeneralchange-makingproblem?Wegivethefollowingexample,Example:d1=7c,d2=5c,d3=1c,andn=10c,notalwaysproducesanoptimalsolution.infact,forsomeinstances,theproblemmaynothaveasolutionatall!considerinstanced1=7c,d2=5c,d3=3c,andn=11c.But,thisproblemcanbesolvedbydynamicprogramming,pleasetrytodesignanalgorithmforthegeneralchange-makingproblemafterclass.GeneralChange-MakingProblemGGreedyAlgorithmsAgreedyalgorithmmakesalocallyoptimalchoicestepbystepinthehopethatthischoicewillleadtoagloballyoptimalsolution.
Thechoicemadeateachstepmustbe:FeasibleSatisfytheproblem’sconstraintslocallyoptimalBethebestlocalchoiceamongallfeasiblechoicesIrrevocableOncemade,thechoicecan’tbechangedonsubsequentsteps.Dogreedyalgorithmsalwaysyieldoptimalsolutions?Example:changemakingproblemwithadenominationsetof7,5and1,andn=10?GreedyAlgorithmsAgreedyalgoApplicationsoftheGreedyStrategyOptimalsolutions:someinstancesofchangemakingMinimumSpanningTree(MST)Single-sourceshortestpathsHuffmancodesApproximations:TravelingSalesmanProblem(TSP)KnapsackproblemotheroptimizationproblemsForsomeproblems,yieldsanoptimalsolutionforeveryinstance.Formost,doesnotbutcanbeusefulforfastapproximations.ApplicationsoftheGreedyStrMinimumSpanningTree(MST)SpanningtreeofaconnectedgraphGisaconnectedacyclicsubgraph(tree)ofGthatincludesallofG’svertices.Note:aspanningtreewithnverticeshasexactlyn-1edges.MinimumSpanningTreeofaweighted,connectedgraphGisaspanningtreeofGofminimumtotalweight.Example:MinimumSpanningTree(MST)SpaMSTProblemGivenaconnected,undirected,weightedgraphG=(V,E),findaminimumspanningtreeforit.ComputeMSTthroughBruteForce?Kruskal:1956,Prim:1957BruteforceGenerateallpossiblespanningtreesforthegivengraph.Findtheonewithminimumtotalweight.FeasibilityofBruteforcePossibletoomanytrees(exponentialfordensegraphs)MSTProblemGivenaconnected,ThePrim’sAlgorithmIdeaofthePrim’salgorithmPseudo-codeofthealgorithmCorrectnessofthealgorithm(important)TimecomplexityofthealgorithmThePrim’sAlgorithmIdeaofthIdeaofPrimGrowasingletreebyrepeatedlyaddingtheleastcostedge(greedystep)thatconnectsavertexintheexistingtreetoavertexnotintheexistingtreeIntermediatesolutionisalwaysasubtreeofsomeminimumspanningtree.IdeaofPrimGrowasingletreePrim’sMSTalgorithmStartwithatree,T0,consistingofonevertex“Grow”treeonevertex/edgeatatimeConstructaseriesofexpandingsubtreesT1,T2,…Tn-1..AteachstageconstructTifromTi-1byaddingtheminimumweightedgethatconnectingavertexintree(Ti-1)toavertexnotyetinthetreethisisthe“greedy”step!AlgorithmstopswhenallverticesareincludedPrim’sMSTalgorithmStartwithPseudocodeofthePrimALGORITHMPrim(G)//Prim’salgorithmforconstructingaminimumspanningtree//Input:AweightedconnectedgraphG=(V,E)//Output:ET,thesetofedgescomposingaminimumspanningtreeofGVT{v0}//v0canbearbitrarilyselectedETfor
i1to|V|-1dofindaminimum-weightedgee*=(v*,u*)amongalltheedges(v,u)suchthatvisinVTanduisinV-VT
VTVT{u*}
ETET{e*}return
ETPseudocodeofthePrimALGORITHAnexampleaedcb1524637Anexampleaedcb1524637ThePrim’salgorithmisgreedy!Thechoiceofedgesaddedtocurrentsubtreesatisfyingthethreepropertiesofgreedyalgorithms.Feasible,eachedgeaddedtothetreedoesnotresultinacycle,guaranteethatthefinalETisaspanningtreeLocaloptimal,eachedgeselectedtothetreeisalwaystheonewithminimumweightamongalltheedgescrossingVTandV-VTIrrevocable,onceanedgeisaddedtothetree,itisnotremovedinsubsequentsteps.ThePrim’salgorithmisgreedyCorrectnessofPrimProvebyinductionthatthisconstructionprocessactuallyyieldsMST.T0isasubsetofallMSTsSupposethatTi-1isasubsetofsomeMSTT,weshouldprovethatTiwhichisgeneratedfromTi-1isalsoasubsetofsomeMST.Bycontradiction,assumethatTidoesnotbelongtoanyMST.Letei=(u,v)betheminimumweightedgefromavertexinTi-1toavertexnotinTi-1usedbyPrim’salgorithmtoexpandingTi-1toTi,accordingtoourassumption,eicannotbelongtoMSTT.AddingeitoTresultsinacyclecontaininganotheredgee’=(u’,v’)connectingavertexu’inTi-1toavertexv’notinit,andw(e’)w(ei)accordingtothegreedyPrim’salgorithm.Removinge’fromTandaddingeitoTresultsinanotherspanningtreeT’withweightw(T’)w(T),indicatingthatT’isaminimumspanningtreeincludingTiwhichcontradicttoassumptionthatTidoesnotbelongtoanyMST.CorrectnessofPrimProvebyinCorrectnessofPrimCorrectnessofPrimImplementationofPrimHowtoimplementthestepsinthePrim’salgorithm?Firstidea,labeleachvertexwitheither0or1,1representsthevertexinVT,and0otherwise.Traversetheedgesettofindanminimumweightedgewhoseendpointshavedifferentlabels.Timecomplexity:O(VE)ifadjacencylinkedlistandO(V3)foradjacencymatrixForsparsegraphs,useadjacencylinkedlistAnyimprovement?ImplementationofPrimHowtoiNotationsT:theexpandingsubtree.Q:theremainingvertices.Ateachstage,thekeypointofexpandingthecurrentsubtreeTistoDeterminewhichvertexinQisthenearestvertextoT.Qcanbethoughtofasapriorityqueue:Thekey(priority)ofeachvertex,key[v],meanstheminimumweightedgefromvtoavertexinT.Key[v]is∞ifvisnotlinkedtoanyvertexinT.Themajoroperationistotofindanddeletethenearestvertex(v,forwhichkey[v]isthesmallestamongallthevertices)RemovethenearestvertexvfromQandadditandthecorrespondingedgetoT.Withtheoccurrenceofthataction,thekeyofv’sneighborswillbechanged.ToremembertheedgesoftheMST,anarray[]isintroducedtorecordtheparentofeachvertex.Thatis[v]isthevertexintheexpandingsubtreeTthatisclosesttovnotinT.NotationsT:theexpandingsubtAdvancedPrim’sAlgorithmALGORITHMMST-PRIM(G,w,r)//w:weight;r:root,thestartingvertexforeachu
V[G]
do
key[u]
[u]NIL
//[u]:theparentofukey[r]0QV[G] //Nowthepriorityqueue,Q,hasbeenbuilt.while
Q
douExtract-Min(Q)//removethenearestvertexfromQ
foreachvAdj[u]//updatethekeyforeachofv’sadjacentnodes.
do
if
vQandw(u,v)<key[v]
then
[v]ukey[v]w(u,v)AdvancedPrim’sAlgorithmALGO国外算法设计与分析课件2TimeComplexityofPrim’salgorithmNeedpriorityqueueforlocatingthenearestvertexUseunorderedarraytostorethepriorityqueue: Efficiency:Θ(n2)Usebinarymin-heaptostorethepriorityqueue Efficiency:Forgraphwithnverticesandmedges:
O(mlogn)UseFibonacci-heaptostorethepriorityqueue:Efficiency:Forgraphwithnverticesandmedges:
O(nlogn+m)TimeComplexityofPrim’salgoKruskal’sMSTAlgorithmEdgesareinitiallysortedbyincreasingweightStartwithanemptyforestF0“grow”MSToneedgeatatimethroughaseriesofexpandingforestsF1,F2,…,Fn-1intermediatestagesusuallyhaveforestoftrees(notconnected)ateachstageaddminimumweightedgeamongthosenotyetusedthatdoesnotcreateacycleneedefficientwayofdetecting/avoidingcyclesalgorithmstopswhenallverticesareincludedKruskal’sMSTAlgorithmEdgesaCorrectnessofKruskalSimilartotheproofofPrimProvebyinductionontheconstructionprocessactuallygenerateaMSTConsiderF0,F1,…,Fn-1CorrectnessofKruskalSimilarBasicKruskal’sAlgorithmALGORITHMKruscal(G)//Input:AweightedconnectedgraphG=<V,E>
//Output:ET,thesetofedgescomposingaminimumspanningtreeofG.SortEinnondecreasingorderoftheedgeweightsw(ei1)<=…<=w(ei|E|) ET
;ecounter
0
//initializethesetoftreeedgesanditssizek0
whileencounter<|V|-1
do kk+1
ifET
U{eik}isacyclic
ET
ETU{eik};ecounterecounter+1returnETBasicKruskal’sAlgorithmALGORKruskal’sAlgorithm(AdvancedPart)Kruskal’sAlgorithm(Advanced国外算法设计与分析课件2Kruskal:TimeComplexity
O(EV)whendisjoint-setdatastructurearenotused.Whenusedisjoint-setdatastructurewithunion-by-rankandpath-compressionheuristics:InitializingthesetAinline1takesO(1)time.
O(V)MAKE-SEToperationsinlines2-3Sorttheedgesinline4takesO(ElogE)time.Theforloopoflines5-8performsO(E)FIND-SETandUNIONoperationsonthedisjoint-setforestb)andd)takeatotalofO((V+E)(V))Line9:O(V+E)Notethat:E
V-1and(V)=O(logV)=O(logE)andEV2SOtotaltimeis:O(ElogV)Kruskal:TimeComplexityO(EV)PropertiesofMSTProperty1:Let(u,v)beaminimum-weightedgeinagraphG=(V,E),then(u,v)belongstosomeminim
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 增资合同协议模板
- 工程代建收费合同协议
- 智能建筑系统集成技术革新与节能降耗应用报告2025
- 商用桌椅转让合同协议
- 香港美容房分租合同协议
- 土壤注浆合同协议
- 牙科入职合同协议
- 研发服务合同补充协议
- 相机出租租赁合同协议
- 2025届江西省南昌市高三二模地理试题 含解析
- T-GXAS 421-2022 成人急性中毒洗胃操作技术规范
- 某高速公路监理管理及工程质量监理要点
- GB/T 3682-2000热塑性塑料熔体质量流动速率和熔体体积流动速率的测定
- GB/T 1931-2009木材含水率测定方法
- 保障宪法实施 加强宪法监督 课件
- 初一下学期期中家长会课件
- 附着式升降脚手架安装验收表
- 高中生物《基因工程的基本操作程序》教案基于学科核心素养的教学设计及教学反思
- 120急救网络医院建设标准
- 研究思路图模板
- BowTie模型简介与应用
评论
0/150
提交评论