版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
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國外算法設(shè)計與分析課件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國外算法設(shè)計與分析課件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國外算法設(shè)計與分析課件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國外算法設(shè)計與分析課件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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 江蘇省徐州市邳州市2024-2025學(xué)年三年級上學(xué)期11月期中英語試題
- 2024-2025學(xué)年福建省三明市五縣聯(lián)考高二(上)期中物理試卷(含答案)
- 醫(yī)用隔離衣產(chǎn)業(yè)規(guī)劃專項研究報告
- 尿布桶產(chǎn)業(yè)深度調(diào)研及未來發(fā)展現(xiàn)狀趨勢
- 拖鞋襪市場發(fā)展預(yù)測和趨勢分析
- 人教版英語八年級下冊 暑假綜合復(fù)習(xí)
- 便攜秤產(chǎn)業(yè)規(guī)劃專項研究報告
- 交通樞紐消防安全維護(hù)方案
- 園藝景觀項目施工方案
- 酒店客房翻新工程方案
- 機(jī)場助航燈光設(shè)計說明
- 2023非心臟外科手術(shù)圍手術(shù)期心血管疾病管理中國專家共識(完整版)
- 山東省淄博市張店區(qū)2022-2023學(xué)年七年級上學(xué)期期中英語試卷
- 【勞動教育項目案例一等獎】“追根稻底”-小學(xué)勞動項目實(shí)踐活動方案
- 電氣火災(zāi)消防安全培訓(xùn)課件
- 齒輪泵泵體的加工工藝與專用夾具設(shè)計說明書
- 04.第四講 堅持以人民為中心
- 甲狀腺癌診療指南
- fg-400變頻器說明書
- jgd280同步控制器使用說明
- 2023年國債資金管理辦法
評論
0/150
提交評論