Tải bản đầy đủ - 0 (trang)
Chapter 17. Graph Properties and Types

Chapter 17. Graph Properties and Types

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

algorithmsknown.

Toillustratethediversityofapplicationsthatinvolvegraph

processing,webeginourexplorationofalgorithmsinthisfertile

areabyconsideringseveralexamples.

MapsApersonwhoisplanningatripmayneedtoanswer

questionssuchas"Whatistheleastexpensivewaytogetfrom

PrincetontoSanJose?"Apersonmoreinterestedintimethan

inmoneymayneedtoknowtheanswertothequestion"What

isthefastestwaytogetfromPrincetontoSanJose?"Toanswer

suchquestions,weprocessinformationaboutconnections

(travelroutes)betweenitems(townsandcities).

HypertextsWhenwebrowsetheWeb,weencounter

documentsthatcontainreferences(links)tootherdocuments

andwemovefromdocumenttodocumentbyclickingonthe

links.TheentireWebisagraph,wheretheitemsare

documentsandtheconnectionsarelinks.Graph-processing

algorithmsareessentialcomponentsofthesearchenginesthat

helpuslocateinformationontheWeb.

CircuitsAnelectriccircuitcompriseselementssuchas

transistors,resistors,andcapacitorsthatareintricatelywired

together.Weusecomputerstocontrolmachinesthatmake

circuitsandtocheckthatthecircuitsperformdesiredfunctions.

Weneedtoanswersimplequestionssuchas"Isashort-circuit

present?"aswellascomplicatedquestionssuchas"Canwelay

outthiscircuitonachipwithoutmakinganywirescross?"In

thiscase,theanswertothefirstquestiondependsononlythe

propertiesoftheconnections(wires),whereastheanswerto

thesecondquestionrequiresdetailedinformationaboutthe

wires,theitemsthatthosewiresconnect,andthephysical

constraintsofthechip.

SchedulesAmanufacturingprocessrequiresavarietyoftasks

tobeperformed,underasetofconstraintsthatspecifiesthat

certaintaskscannotbestarteduntilcertainothertaskshave



beencompleted.Werepresenttheconstraintsasconnections

betweenthetasks(items),andwearefacedwithaclassical

schedulingproblem:Howdoweschedulethetaskssuchthat

webothrespectthegivenconstraintsandcompletethewhole

processintheleastamountoftime?

TransactionsAtelephonecompanymaintainsadatabaseof

telephone-calltraffic.Heretheconnectionsrepresenttelephone

calls.Weareinterestedinknowingaboutthenatureofthe

interconnectionstructurebecausewewanttolaywiresand

buildswitchesthatcanhandlethetrafficefficiently.Asanother

example,afinancialinstitutiontracksbuy/sellordersina

market.Aconnectioninthissituationrepresentsthetransferof

cashbetweentwocustomers.Knowledgeofthenatureofthe

connectionstructureinthisinstancemayenhanceour

understandingofthenatureofthemarket.

MatchingStudentsapplyforpositionsinselectiveinstitutions

suchassocialclubs,universities,ormedicalschools.Items

correspondtothestudentsandtheinstitutions;connections

correspondtotheapplications.Wewanttodiscovermethods

formatchinginterestedstudentswithavailablepositions.

NetworksAcomputernetworkconsistsofinterconnectedsites

thatsend,forward,andreceivemessagesofvarioustypes.We

areinterestednotjustinknowingthatitispossibletogeta

messagefromeverysitetoeveryothersitebutalsoin

maintainingthisconnectivityforallpairsofsitesasthenetwork

changes.Forexample,wemightwishtocheckagivennetwork

tobesurethatnosmallsetofsitesorconnectionsissocritical

thatlosingitwoulddisconnectanyremainingpairofsites.

ProgramstructureAcompilerbuildsgraphstorepresent

realtionshipsamongmodulesinalargesoftwaresystem.The

itemsarethevariousclassesormodulesthatcomprisethe

system;connectionsareassociatedeitherwiththepossibility

thatamethodinoneclassmightinvokeanother(static

analysis)orwithactualinvocationswhilethesystemisin



operation(dynamicanalysis).Weneedtoanalyzethegraphto

determinehowbesttoallocateresourcestotheprogrammost

efficiently.

Theseexamplesindicatetherangeofapplicationsforwhich

graphsaretheappropriateabstractionandalsotherangeof

computationalproblemsthatwemightencounterwhenwework

withgraphs.Suchproblemswillbeourfocusinthisbook.In

manyoftheseapplicationsastheyareencounteredinpractice,

thevolumeofdatainvolvedistrulyhuge,andefficient

algorithmsmakethedifferencebetweenwhetherornota

solutionisatallfeasible.

Wehavealreadyencounteredgraphs,briefly,inPart1.Indeed,

thefirstalgorithmsthatweconsideredindetail,theunion-find

algorithmsinChapter1,areprimeexamplesofgraph

algorithms.WealsousedgraphsinChapter3asanillustration

ofapplicationsoftwo-dimensionalarraysandlinkedlistsandin

Chapter5toillustratetherelationshipbetweenrecursive

programsandfundamentaldatastructures.Anylinkeddata

structureisarepresentationofagraph,andsomefamiliar

algorithmsforprocessingtreesandotherlinkedstructuresare

specialcasesofgraphalgorithms.Thepurposeofthischapteris

toprovideacontextfordevelopinganunderstandingofgraph

algorithmsrangingfromthesimpleonesinPart1tothe

sophisticatedonesinChapters18through22.

Asalways,weareinterestedinknowingwhicharethemost

efficientalgorithmsthatsolveaparticularproblem.Thestudyof

theperformancecharacteristicsofgraphalgorithmsis

challengingbecause

Thecostofanalgorithmdependsnotjustonpropertiesof

thesetofitemsbutalsoonnumerouspropertiesoftheset

ofconnections(andglobalpropertiesofthegraphthatare

impliedbytheconnections).



Accuratemodelsofthetypesofgraphsthatwemightface

aredifficulttodevelop.

Weoftenworkwithworst-caseperformanceboundsongraph

algorithms,eventhoughtheymayrepresentpessimistic

estimatesonactualperformanceinmanyinstances.

Fortunately,asweshallsee,anumberofalgorithmsare

optimalandinvolvelittleunnecessarywork.Otheralgorithms

consumethesameresourcesonallgraphsofagivensize.We

canpredictaccuratelyhowsuchalgorithmswillperformin

specificsituations.Whenwecannotmakesuchaccurate

predictions,weneedtopayparticularattentiontopropertiesof

thevarioustypesofgraphsthatwemightexpectinpractical

applicationsandmustassesshowthesepropertiesmightaffect

theperformanceofouralgorithms.

Webeginbyworkingthroughthebasicdefinitionsofgraphsand

thepropertiesofgraphs,examiningthestandardnomenclature

thatisusedtodescribethem.Followingthat,wedefinethe

basicADT(abstractdatatype)interfacesthatweusetostudy

graphalgorithmsandthetwomostimportantdatastructures

forrepresentinggraphstheadjacency-matrixrepresentationand

theadjacency-listsrepresentation,andvariousapproachesto

implementingbasicADToperations.Then,weconsiderclient

programsthatcangeneraterandomgraphs,whichwecanuse

totestouralgorithmsandtolearnpropertiesofgraphs.Allthis

materialprovidesabasisforustointroducegraph-processing

algorithmsthatsolvethreeclassicalproblemsrelatedtofinding

pathsingraphs,whichillustratethatthedifficultyofgraph

problemscandifferdramaticallyevenwhentheymightseem

similar.Weconcludethechapterwithareviewofthemost

importantgraph-processingproblemsthatweconsiderinthis

book,placingthemincontextaccordingtothedifficultyof

solvingthem.



19.3ReachabilityandTransitiveClosure

Todevelopefficientsolutionstoreachabilityproblemsin

digraphs,webeginwiththefollowingfundamentaldefinition.

Definition19.5Thetransitiveclosureofadigraphisa

digraphwiththesameverticesbutwithanedgefromstotin

thetransitiveclosureifandonlyifthereisadirectedpathfrom

stotinthegivendigraph.

Inotherwords,adigraph'stransitiveclosurehasanedgefrom

eachvertextoalltheverticesreachablefromthatvertexinthe

digraph.Clearly,thetransitiveclosureembodiesalltherequisite

informationforsolvingreachabilityproblems.Figure19.13

illustratesasmallexample.



Figure19.13.Transitiveclosure

Thisdigraph(top)hasjusteightdirectededges,butits

transitiveclosure(bottom)showsthattherearedirectedpaths

connecting19ofthe30pairsofvertices.Structuralproperties

ofthedigrapharereflectedinthetransitiveclosure.For

example,rows0,1,and2intheadjacencymatrixforthe

transitiveclosureareidentical(asarecolumns0,1,and2)

becausethoseverticesareonadirectedcycleinthedigraph.



Oneappealingwaytounderstandthetransitiveclosureisbased

onadjacency-matrixdigraphrepresentations,andonthe

followingbasiccomputationalproblem:

BooleanmatrixmultiplicationABooleanmatrixisamatrix

whoseentriesareallbinaryvalues,eitherfalseortrue.Given

twoBooleanmatricesAandB,computeaBooleanproduct

matrixC,usingthelogicalandandoroperationsinsteadofthe

arithmeticoperations*and+,respectively.

ThetextbookalgorithmforcomputingtheproductoftwoV-byVmatricescomputes,foreachsandt,thedotproductofrows

inthefirstmatrixandrowtinthesecondmatrix,asfollows:



for(s=0;s
for(t=0;t
for(i=0,C[s][t]=0;i
C[s][t]+=A[s][i]*B[i][t];

Inmatrixnotation,wewritethisoperationsimplyasC=A*B.

Thisoperationisdefinedformatricescomprisinganytypeof

entryforwhich0,+,and*aredefined.Inparticular,ifthe

matrixentriesareeithertrueorfalseandweinterpreta+bto

bethelogicaloroperationanda*btobethelogicaland

operation,thenwehaveBooleanmatrixmultiplication.InJava,



wecanusethefollowingversion:



for(s=0;s
for(t=0;t
for(i=0,C[s][t]=false;i
if(A[s][i]&&B[i][t])C[s][t]=true;

TocomputeC[s][t]intheproduct,weinitializeittofalse,

thensetittotrueifwefindsomevalueiforwhichbothA[s]

[i]andB[i][t]arebothtrue.Runningthiscomputationis

equivalenttosettingC[s][t]totrueifandonlyiftheresultof

abitwiselogicalandofrowsinAwithcolumntinBhasa

nonzeroentry.

NowsupposethatAistheadjacencymatrixofadigraphAand

thatweusetheprecedingcodetocomputeC=A*A A2

(simplybychangingthereferencetoBinthecodeintoa

referencetoA).Readingthecodeintermsoftheinterpretation

oftheadjacency-matrixentriesimmediatelytellsuswhatit

computes:Foreachpairofverticessandt,weputanedge

fromstotinCifandonlyifthereissomevertexiforwhich

thereisbothapathfromstoiandapathfromitotinA.In

otherwords,directededgesinA2correspondpreciselyto

directedpathsoflength2inA.Ifweincludeself-loopsatevery

vertexinA,thenA2alsohastheedgesofA;otherwise,itdoes

not.ThisrelationshipbetweenBooleanmatrixmultiplicationand

pathsindigraphsisillustratedinFigure19.14.Itleads

immediatelytoanelegantmethodforcomputingthetransitive

closureofanydigraph.



Figure19.14.Squaringanadjacencymatrix

Ifweput0sonthediagonalofadigraph'sadjacencymatrix,



thesquareofthematrixrepresentsagraphwithanedge

correspondingtoeachpathoflength2(top).Ifweput1son

thediagonal,thesquareofthematrixrepresentsagraphwith

anedgecorrespondingtoeachpathoflength1or2(bottom).



Property19.6

Wecancomputethetransitiveclosureofadigraphby

constructingthelatter'sadjacencymatrixA,addingself-loops

foreveryvertex,andcomputingAV.

Proof:Continuingtheargumentinthepreviousparagraph,A3

hasanedgeforeverypathoflengthlessthanorequalto3in

thedigraph,A4hasanedgeforeverypathoflengthlessthan

orequalto4inthedigraph,andsoforth.Wedonotneedto

considerpathsoflengthgreaterthanVbecauseofthe

pigeonholeprinciple:Anysuchpathmustrevisitsomevertex

(sincethereareonlyVofthem)andthereforeaddsno

informationtothetransitiveclosurebecausethesametwo

verticesareconnectedbyadirectedpathoflengthlessthanV

(whichwecouldobtainbyremovingthecycletotherevisited

vertex).



Figure19.15showstheadjacency-matrixpowersforasample

digraphconvergingtotransitiveclosure.ThismethodtakesV

matrixmultiplications,eachofwhichtakestimeproportionalto

V3,foragrandtotalofV4.Wecanactuallycomputethe

transitiveclosureforanydigraphwithjust lgV Boolean

matrix-multiplicationoperations:WecomputeA2,A4,A8,...

untilwereachanexponentgreaterthanorequaltoV.As

shownintheproofofProperty19.6,At=AVforanyt>V;so

theresultofthiscomputation,whichrequirestimeproportional

toV3lgV,isAVthetransitiveclosure.



Figure19.15.Adjacencymatrixpowersand

directedpaths

Thissequenceshowsthefirst,second,third,andfourthpowers

(right,toptobottom)oftheadjacencymatrixatthetopright,

whichgivesgraphswithedgesforeachofthepathsoflengths

lessthan1,2,3,and4,respectively,(left,toptobottom)in

thegraphthatthematrixrepresents.Thebottomgraphisthe

transitiveclosureforthisexample,sincetherearenopathsof

lengthgreaterthan4thatconnectverticesnotconnectedby

shorterpaths.



Althoughtheapproachjustdescribedisappealinginits

simplicity,anevensimplermethodisavailable.Wecancompute

thetransitiveclosurewithjustoneoperationofthiskind,

buildingupthetransitiveclosurefromtheadjacencymatrixin

place,asfollows:



for(i=0;i
for(s=0;s
for(t=0;t
if(A[s][i]&&A[i][t])A[s][t]=true;

Thisclassicalmethod,inventedbyS.Warshallin1962,isthe

methodofchoiceforcomputingthetransitiveclosureofdense

digraphs.Thecodeissimilartothecodethatwemighttryto

usetosquareaBooleanmatrixinplace:Thedifference(which

issignificant!)liesintheorderoftheforloops.



Property19.7

WithWarshall'salgorithm,wecancomputethetransitive

closureofadigraphintimeproportionaltoV3.

Proof:Therunningtimeisimmediatelyevidentfromthe

structureofthecode.Weprovethatitcomputesthetransitive

closurebyinductiononi.Afterthefirstiterationoftheloop,

thematrixhastrueinrowsandcolumntifandonlyifthe

digraphhaseithertheedges-torthepaths-0-t.Thesecond

iterationchecksallthepathsbetweensandtthatinclude1

andperhaps0,suchass-1-t,s-1-0-t,ands-0-1-t.Weare

ledtothefollowinginductivehypothesis:Theithiterationof

theloopsetsthebitinrowsandcolumntinthematrixto

trueifandonlyifthereisadirectedpathfromstotinthe

digraphthatdoesnotincludeanyverticeswithindicesgreater

thani(exceptpossiblytheendpointssandt).Asjustargued,

theconditionistruewheniis0,afterthefirstiterationofthe

loop.Assumingthatitistruefortheithiterationoftheloop,

thereisapathfromstotthatdoesnotincludeanyvertices

withindicesgreaterthani+1ifandonlyif(i)thereisapath

fromstotthatdoesnotincludeanyverticeswithindices

greaterthani,inwhichcaseA[s][t]wassetonaprevious

iterationoftheloop(bytheinductivehypothesis);or(ii)there

isapathfromstoi+1andapathfromi+1tot,neitherof

whichincludesanyverticeswithindicesgreaterthani(except

endpoints),inwhichcaseA[s][i+1]andA[i+1][t]were

previouslysettotrue(byhypothesis),sotheinnerloopsets

A[s][t].



WecanimprovetheperformanceofWarshall'salgorithmwitha

simpletransformationofthecode:WemovethetestofA[s]



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

Chapter 17. Graph Properties and Types

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

×