Você está na página 1de 186

13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.

LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina1

580 Captulo21Estructurasdedatosparaconjuntosdisjuntos

PorqueyesunarazantesdelaLINK,q1.y/D.N/y:rango.LaLTINTA
Operacindejaycomounaraz,ydejaelrangodeysolooincrementay
rankingpor1.Porlotanto,yasea.yQ1q.y/D/oq.y/DQ1.y/C.N/.
ElaumentoenelpotencialdebidoalaoperacinLINK,porlotanto,esalosumo.N/.
ElcosteamortizadodelaoperacinLINKesO.1/C.N/DO..n//.

Lema21.13
ElcosteamortizadodecadaoperacinFINDSETesO..n//.

PruebaSupongamosquelaoperacinqthesunETFINDSyqueelcaminoconhallazgo
Snodos.ElcosterealdelaoperacinFINDSETesS/.Deberiamos
muestranquelosaumentospotencialesnodenodo,debidoalaFINDSETyquealmenos
Mx.0S ..n/C2//losnodosdelatrayectoriadebsquedatienensupotencialdedisminucin
Almenos1.
Paraverqueelpotencialdeningnnodoaumenta,primeroapelamosalLemma21.10paratodos
Nodosdistintosdelaraz.Sixeslaraz,acontinuacin,supotencialse.N/x:rango,elcual
nocambia.
Ahoramostramosquealmenosmax.0S..n/C2//nodostienensupotencial
disminucindealmenos1.SeaXunnodoenelcaminohallazgotalesquex:rango>0
Yxesseguidoenalgnlugardelarutadebsquedaporotronodoyquenoesunaraz,
dondelevel.y/Dlevel.x/justoantesdelaoperacinFINDSET.(Nodeynonecesita
seguirinmediatamentexenelcaminodebsqueda.)Todos,peroenlamayora.N/C2nodosenelhallazgo
Pathsatisfacenestasrestriccionesenx.Losquenolossatisfacensonelprimernodo
Enelcaminodebsqueda(sitienerango0),elltimonodoenelcamino(esdecir,laraz)yel
ltimonodowenlatrayectoriaparalacuallevel.w/Dk,paracadakD012:::.n/1.
Vamosafijartalnodox,ymostraremosqueelpotencialdexdisminuyeporat
Menos1.DejekDlevel.x/Dlevel.y/.Justoantesdelacompresindelatrayectoriacausadapor
elFINDSET,tenemos
x:p:rango UN.iter.x//
.X:Rango/(pordefinicindeiter.x/),
K
y:t:rango Unk.y:Rango/ (Pordefinicindenivel.y/),
y:rango x:p:rango (PorelCorolario21.5yporque
Ysiguexenlatrayectoriadebsqueda).
Poniendoestasdesigualdadesjuntasydejandoqueseaelvalordeiter.x/beforepath
Compresin,tenemos
y:t:rango Unk.y:Rango/
A.xk:p:Rango/ (porqueA.Jk/esestrictamentecreciente)
Ak.A.iter.x//
.X://rango
K
DA .iC1/.X:Rango/:
K

Pgina2

21.4Anlisisdeuninporrangoconcompresindetrayectoria 581

Debidoaquelacompresinderutaharquexeytenganelmismopadre,sabemos
quedespusdecompresindecaminos,x:p:Drangoy:t:rangoyquelacompresindecaminos
nodisminuyey:t:rango.Comox:rangonocambia,despusdelacompresindecaminos
tenemosquex:p:rango UN .iC1/.X:Rango/.Porlotanto,lacompresinderutacausar
K
Iter.x/paraaumentar(almenosiC1)olevel.x/paraaumentar(loqueocurresi
iter.x/aumentahastaalmenosx:rangoC1).Encualquiercaso,porelLema21.10,tenemos
q.x/q1.x/1.Porlotanto,losposiblesdisminucionesdexporlomenos1.
ElcosteamortizadodelaoperacinFINDSETeselcostorealmselcambio
Enpotencial.ElcostorealesOs/,yhemosdemostradoqueelpotencialtotal
Disminuyealmenosenunmximode0S..n/C2//.Elcostoamortizado,porlo
MsOs/.s..n/C2//DOs/sCO..n//DO..n//,yaquepodemos
EscalarlasunidadesdepotencialparadominarlaconstanteocultaenOs/.

Poniendojuntosloslemasprecedentesseobtieneelsiguienteteorema.

Teorema21.14
https://translate.googleusercontent.com/translate_f 1/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
UnasecuenciadeAKEmMSET,Unin,yFINDSEToperaciones,delascualessonn
OperacionesSEGRESESET,sepuedenrealizarenunbosquedisjuntossetconlauninpor
RangoycompresinderutaenelpeordeloscasosOm.n//.

LapruebainmediatadeLemmas21.7,21.11,21.12,21.13y.

Ceremonias

21.41
ProbarLemma21.4.

21.42
Demuestrequecadanodotienerangoenlamayoradeblgnc.

21,43
AlaluzdeEjercicio21,42,elnmerodebitsnecesariosparaalmacenarx:clasificacindecada
Nodox

21,44
Usandoelejercicio21.42,dunasimplepruebadequelasoperacionesenunbosqueconjuntodisjunto
ConuninporrangoperosincompresindetrayectoriaenO.mlgn/time.

21,45
ElprofesorDanterazonaquedebidoaquelasfilasdenodosaumentanestrictamente
Rutaalaraz,losnivelesdenododebenmonotonicallyaumentaralolargodelaruta.Enotra

Pgina3

582 Captulo21Estructurasdedatosparaconjuntosdisjuntos

Esdecir,six:rango>0yx:pnoesunaraz,entonceslevel.x/level.x:p/.Esel
Profesorcorrecto

21,46?
Considerelafuncin0.n/DminfkWA0,1k/ Lg.nC$$/g.Demostrarque0.n/A3
Paratodoslosvaloresprcticosdeny,usandoelejercicio21.42,muestrancmomodificarel
posibleargumentofuncinparademostrarquepodemosrealizarunasecuenciademSEGRESE
SET,Unin,yFINDSEToperaciones,ndeloscualessonoperacionesSEGRESESET,en
Unbosqueconjuntodisjuntoconuninporrangoycompresindelatrayectoriaenelpeordeloscasos
OM0//.n.

Problemas

211Mnimofueradelnea
ElproblemamnimafueradelneanospidequemantenerunconjuntoTdinmicodeelementos
Desdeeldominiof12:::ngbajolasoperacionesdeEyEnsertXTRACTMEN.
SenosdaunasecuenciadenSInsertymEXTRACTMENllamadas,dondecada
Claveenf12:::Ngseinsertaexactamenteunavez.Deseamosdeterminarquclave
sedevuelveporcadallamadaEXTRACTMEN.Especficamente,deseamosrellenarunamatriz
ExtradasOE1::m,dondeporiD12:::m,seextrajoOEIeslaclavequedevuelve
laisimaEXTRACTMENllamada.Elproblemaes"offline"enelsentidodequeestamos
ProcesoStodalasecuenciaSantesdedeterminarcualquieradelas
llaves.

a.Enelcasosiguientedelproblemamnimofueradelnea,cadaoperacin
Mensert.i/estrepresentadoporelvalordeiycadaEXTRACTMINesrepre
PorlaletraE:

48E3E926EEE17E5:

Rellenelosvalorescorrectosdelamatrizextrada.

Paradesarrollarunalgoritmoparaesteproblema,rompemoslasecuenciaSenhomoge
Nuevassubsecuencias.Esdecir,representamosSpor
I1EI2EI3:::ImEIMC1
dondecadaErepresentaunnicoEXTRACTMENllamadaycadaunomejrepresentaun(posi
blementevaco)secuenciadelaInsertllama.ParacadasubsecuenciaIj,queinicialmentecolocamos
lasclavesintroducidasporestasoperacionesenunconjuntoKj,queestvacasijestvaca.
Entonceshacemoslosiguiente:

Pgina4

https://translate.googleusercontent.com/translate_f 2/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

ProblemasparaelCaptulo21 583

OFFLINEMNIMOS.mnorte/
1paraiD1an
2 determinarjtalquei2Kj
3 sijmC1
4 extradaiOEJD
5 Seaelmenorvalormayorquej
paralosqueestableceKlexiste
6 KlDKj[lK,destruyendoKj
7retornoextrada

segundo.ArgumentanquelamatrizextradadevueltoporOFFLINEMNIMOSescorrecta.

do.DescribecmoimplementarOFFLINEMNIMOSdemaneraeficienteconundisjoint
Establecerlaestructuradedatos.Darunlmitefuerteenelpeorcasodetiempodeejecucindesu
implementacin.

212Determinacindelaprofundidad
Enelproblemadelaprofundidaddeterminacin,mantenemosunbosqueFDfTigdearraigada
rbolesbajotresoperaciones:
SEGRESETREE./Creaunrbolcuyoniconodoes.

FINDDEPTH./Devuelvelaprofundidaddelnododentrodesurbol.
GBALSA.r/Hacequeelnodor,quesesuponeeslarazdeunrbol,seconvierteenel
Hijodenodo,quesesuponequeestenunrboldiferenteder,peropuedeopuede
Noserunaraz.

a.Supongamosqueusamosunarepresentacinderbolsimilaraunbosquedisjuntosset::p
eselpadredelnodo,exceptoque:pD Siesunaraz.Supongaque
queponemosenprcticaGBALSA.r/Rporelestablecimiento:pD
yFINDDEPTH.Por
Siguiendolarutadebsquedahastalaraz,devolviendounrecuentodetodoslosnodosquenosean
Encontrados.DemostrarqueelpeordeloscasoseltiempodeunasecuenciademSEGRESEcorriendo
TREE,FINDDEPTH,ylasoperacionesGbalsa,.m2/.

Medianteelusodelaheursticaunionbyrankypathcompression,podemosreducirla
Enelpeordeloscasos.UtilizamoslasSDfSforestalesdisjuntossetig,dondecada
conjuntoSi(queesensmismounrbol)secorrespondeconunrbolTienelbosqueF.Elrbol
estructuradentrodeunconjuntoSi,sinembargo,nosecorrespondenecesariamenteconladeTi.En
Dehecho,laaplicacindeSinoregistralasrelacionesexactasentrepadresehijos
perosinembargonospermitedeterminarlaprofundidaddecualquiernododeTi.
Laideaclaveesmantenerencadanododeuna"pseudodistance":D,lacuales
Definidademaneraquelasumadelaspseudodistanciasalolargodelatrayectoriasimpledela

Pgina5

584 Captulo21Estructurasdedatosparaconjuntosdisjuntos

razdesuconjuntoSiesigualalaprofundidaddeenTi.Esdecir,sielcaminosimpledesu
racesenS
Pk ies01:::k,donde0DykesSi'sdelaraz,entonceslaprofundidadde
enTies jD0j:d.
segundo.DarunaimplementacindeSEGRESETREE.

do.MostrarcmomodificarFINDSETparaimplementarFINDDEPTH.Suimplementacin
Lacompresindelatrayectoriaysutiempodeejecucindebeserlineal
Enlalongituddelatrayectoriadebsqueda.Asegresedequesusactualizacionesdeimplementacin
Pseudodistancescorrectamente.

re.MostrarcmoimplementarGBALSA.r/,Quecombinalosconjuntosquecontienenr
y,mediantelamodificacindelosprocedimientosdeUnin yLtinta.Asegresedequesu
Implementacinactualizapseudodistancescorrectamente.TengaencuentaquelarazdeunconjuntoSi
noesnecesariamentelarazdelrbolcorrespondienteTi.

mi.DarunapretadocondestinoenelpeordeloscasoseltiempodeunasecuenciademSEGRESEcorriendo
TREE,FINDDEPTH,yGBALSAoperaciones,ndeloscualessonSEGRESETREEopcin
Ciones.

213ElalgoritmodelosantepasadosmenoscomunesdeTarjan
Elantepasadocomndeporlomenosdosnodosuyenunacamisetarbolconrazeselnodow
QueesunantepasadodeuyyquetienelamayorprofundidadenT.Enel
fueradelneaproblemamnimocomnantepasados,senosdaunacamisetayunrbolarraigado
ConjuntoarbitrarioPDffuGgdeparesnoordenadosdenodosenT,ydeseamosdeter
MinaelantepasadomenoscomndecadaparenP.
Pararesolverelproblemadelosantepasadosmenoscomunescomunes,elsiguienteprocedimiento
realizaunrecorridodelrboldeTconlaLCA.Tllamadainicial:root/.Suponemosquecada
https://translate.googleusercontent.com/translate_f 3/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
nodoesdecolorBLANCOantesdelacaminata.

LCA.u/
1SEGRESESET.u/
2FINDSET.u/:Duancestro
3paracadaniodeuenT
4 LCA./
5 UNIN.U/
6 FINDSET.u/:Duancestro
7u:DColorNEGRO
8paracadanododetalmaneraquefuG2P
9 si:elcolorNEGRO==
10 Print"Elantepasadomenoscomnde"
u"y""es"FINDSET./:Ancestro

Pgina6

Notasparaelcaptulo21 585

a.Argumentanquelalnea10seejecutaexactamenteunavezporcadaparfuG2p

segundo.ArgumentanqueenelmomentodelallamadaLCA.u/,elnmerodeconjuntosenelconjuntodisjunto
LaestructuradedatosesigualalaprofundidaddeuenT.

do.ProbarqueLCAimprimecorrectamenteelantepasadomenoscomndeuyparacadauno
PairfuG2p

re.AnalizareltiempodeejecucindelaLCA,suponiendoqueusamoslaimplementacinde
LaestructuradedatosdeconjuntosdisjuntosenlaSeccin21.3.

Notasdelcaptulo

Muchosdelosresultadosimportantesparalasestructurasdedatosdeconjuntosdisjuntossedebenalmenosenparte
ARETarjan.Usandoelanlisisagregado,Tarjan[328,330]dioelprimerapretado
Lmitesuperiorentrminosdelainversay.mdecrecimientomuylentoN/deAckermann's
funcin.(LafuncinA.Jk/dadaenlaseccin21.4essimilaraladeAckermann
,Ylafuncin.n/essimilaralainversa.Ambos.n/yy.mnorte/
Soncomomximo4paratodoslosvaloresconcebiblesdemyn.)UnO.mlgn/lmitesuperior
FuedemostradoanteriormenteporHopcroftyUllman[5,179].EltratamientoenlaSeccin21.4
SeadaptaapartirdeunanlisisposteriordeTarjan[332],queasuvezsebasaenunaanal
YsisporKozen[220].HarfstyReingold[161]danunaversinpotencialdela
EllmiteanteriordeTarjan.
TarjanyvanLeeuwen[333]discutirlasvariantesdelarutadecompresinheuris
Tic,incluidoslos"mtodosdeunasolapasada",queavecesofrecenmejoresfactoresconstantes
Ensudesempeoquelosmtodosdedospasos.AligualqueconlosanterioresanlisisdeTarjan
Delaheursticabsicadelatrayectoriacompresin,losanlisisdeTarjanydevanLeeuwen
Sonagregados.HarfstyReingold[161]mostraronmstardecmohacerunpequeocambio
Alafuncinpotencialparaadaptarsuanlisisdecompresindetrayectoriaaestos
VariantesGabowyTarjan[121]muestranqueenciertasaplicaciones,elconjuntodisjunto
LasoperacionessepuedenhacerfuncionarenOm/tiempo.
Tarjan[329]demostrqueunlmiteinferiorde.my.mN//tiemponecesariopara
Operacionessobrecualquierestructuradedatosdeconjuntodisyuntivoquesatisfagaciertascondicionestcnicas.
EstelmiteinferiorfuegeneralizadomstardeporFredmanySaks[113],quemostr
Queenelpeordeloscasos,.my.mN//.lgn/bitpalabrasdememoriadebenseraccedidas.

Pgina7

https://translate.googleusercontent.com/translate_f 4/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

VIGrficoAlgoritmos

Pgina8

Introduccin

Losproblemasdelosgrficosimpregnanlainformticaylosalgoritmosparatrabajarconellos
Sonfundamentalesparaelcampo.Cientosdeproblemascomputacionalesinteresantesson
Expresadoentrminosdegrficos.Enestaparte,tocamosalgunosdelosmssignificativos
Otros.
Elcaptulo22muestracmopodemosrepresentarungrficoenunacomputadorayluego
Algoritmosbasadosenlabsquedadeungrficoutilizandobienlaanchuradelaprimerabsquedaoprofundidad
Primerabsqueda.Elcaptuloofrecedosaplicacionesdebsquedadeprofundidad:topolgica
Clasificarungrficoacclicodirigidoydescomponerungrficodirigidoensufuerte
Componentesconectados.
Elcaptulo23describecmocalcularunrboldeexpansindepesomnimo
Grfica:laformademenorpesodeconectartodoslosvrticescuandocada
Elbordetieneunpesoasociado.Losalgoritmosparacalcularelalcancemnimo
Losrbolessirvencomobuenosejemplosdealgoritmoscodiciosos(vaseelcaptulo16).
Loscaptulos24y25considerancmocalcularlostrayectosmscortosentrelosvrtices
Cuandocadabordetieneunalongitudo"peso"asociado.ElCaptulo24muestracmo
Encontrarlastrayectoriasmscortasdeunvrticedefuentedadoatodoslosotrosvrtices,yelCaptulo25
Examinamtodosparacalcularloscaminosmscortosentrecadapardevrtices.
Finalmente,elCaptulo26muestracmocalcularunflujomximodematerialenunflujo
Red,queesungrafodirigidoquetieneunvrticefuenteespecificadodematerial,un
Especificado,ylascapacidadesespecificadasparalacantidaddematerialquepuede
Atravesarcadabordedirigido.Esteproblemageneralsurgeenmuchasformas,y

https://translate.googleusercontent.com/translate_f 5/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Unbuenalgoritmoparacalcularflujosmximospuedeayudararesolverunavariedadde
Problemasdemaneraeficiente.

Pgina9

588 AlgoritmosdegrficosdelaparteVI

Cuandosecaracterizaeltiempodeejecucindeunalgoritmodegrficoenungrficodado
GD.VE/,usualmentemedimoseltamaodelaentradaentrminosdelnmerode
LosvrticesjVjyelnmerodearistasjEjdelgrfico.Esdecir,describimosla
Tamaodelaentradacondosparmetros,noslouno.Adoptamosunanotacincomn
Paraestosparmetros.Dentrodelanotacinasinttica(comoOnotacin
o,notation),yslodentrodeesanotacin,elsmboloVdenotajVjy
ElsmboloEdenotajEj.Porejemplo,podramosdecir,"elalgoritmoseejecutaen
TiempoO.VE/",loquesignificaqueelalgoritmoseejecutaeneltiempoO.jVjjEj/.Estaconvencin
Cinhacequelasfrmulasdetiempodeejecucinseanmsfcilesdeleer,sinriesgodeambigedad.
Otraconvencinqueadoptamosapareceenpseudocdigo.Denotamoselconjuntodevrtices
deungrafoGporG:VysubordefijadoporG:E.Esdecir,elpseudocdigovisualizaelvrtice
Ylosconjuntosdearistascomoatributosdeungrfico.

Pgina10

22 AlgoritmosGrficosElementales

Estecaptulopresentamtodospararepresentarungrficoyparabuscarungrfico.
Buscarungrficosignificaseguirsistemticamentelosbordesdelgrficopara
Visitelosvrticesdelagrfica.Unalgoritmodebsquedadegrficospuededescubrirmucho
Sobrelaestructuradeungrfico.Muchosalgoritmoscomienzanbuscandoensusentradas
Paraobtenerestainformacinestructural.Variosotrosalgoritmosdegrficoselabo
Enlabsquedabsicadegrficos.Lastcnicasparabuscarungrficoestnenelcoraznde
Elcampodealgoritmosdegrficos.
Laseccin22.1discutelasdosrepresentacionescomputacionalesmscomunesde
https://translate.googleusercontent.com/translate_f 6/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Grficos:comolistasdeadyacenciaycomomatricesdeadyacencia.Laseccin22.2presentauna
Algoritmodebsquedadegrficosllamadoamplitudprimerabsquedaymuestracmocre
Comiunrboldeanchoprimero.Laseccin22.3presentaunabsquedaenprofundidadydemuestra
Resultadosestndarsobreelordenenquelaprofundidaddeprimerabsquedavisitavrtices.Segundo
La22.4proporcionanuestraprimeraaplicacinrealdelabsquedaenprofundidad:topolgicamenteordenar
Ungrficoacclicodirigido.Unasegundaaplicacindebsquedaenprofundidad,encontrandola
Componentesfuertementeconectadosdeunagrficadirigida,eseltemadelaSeccin22.5.

22.1Representacionesgrficas

PodemoselegirentredosformasestndarpararepresentarungrficoGD.VE/:
Comounacoleccindelistasdeadyacenciaocomounamatrizdeadyacencia.Decualquiermaneraseaplica
Agrficosdirigidosynodirigidos.Debidoaquelarepresentacindelalistadeadyacencia
proporcionaunaformacompactapararepresentargrficosenlosescasosparalasqueesmuchojej
MenosdejVj2esgeneralmenteelmtododeeleccin.Lamayoradelosalgoritmosdegrficos
Presentadoenestelibroasumequeungrficodeentradaserepresentaenadjacencia
Formulariodelista.Podemospreferirunarepresentacindematrizdeadyacencia,sinembargo,cuandola
grafoesdensojEjestcercadejVj2ocuandonecesitamossercapacesdedecirrpidamente
Sihayunbordequeconectadosvrticesdados.Porejemplo,dosdelasparejas

Pgina11

590 Captulo22Algoritmosdegrficoselementales

12345
1 2 5 1 0 1001
1 2 2 1 5 3 4 2 1 0111
3 2 4 3 0 1010
3
4 2 5 3 4 0 1101
5 4 5 4 1 2 5 1 1010
(un) (segundo) (do)

Figura22.1Dosrepresentacionesdeungrafonodirigido.(a)UngrafoGnodirigidocon5vrtices
Y7bordes.(b)UnarepresentacindeadyacencialistadeG.(c)Larepresentacinpormatrizdeadyacencia
DeG.

12345 6
1 2 4 1 0 1010 0
2 5 2 0 0001 0
1 2 3 3 6 5 3 0 0001 1
4 2 4 0 1000 0
5 4 5 0 0010 0
4 5 6 6 6 6000001
(un) (segundo) (do)

Figura22.2Dosrepresentacionesdeungrafodirigido.(a)UngrficodeGdirigidacon6vrticesy8
Bordes(b)UnarepresentacindeadyacencialistadeG.(c)LarepresentacinpormatrizdeadyacenciadeG.

LosalgoritmosdetrayectosmscortospresentadosenelCaptulo25suponenquesusgrficosdeentrada
Serepresentanpormatricesdeadyacencia.
LarepresentacindeadyacencialistadeunagrficaGD.VE/consisteenunar
AdjrayosdelistasjJV,unaparacadavrticeenV.Paracadau2V,lalistadeadyacencia
Adjoeucontienetodoslosvrticesdetalmaneraquehayunborde.u/2E.Esdecir,
AdjoeusecomponedetodoslosvrticesadyacentesaTenG.(Alternativamente,puedecontener
Punterosaestosvrtices.)Dadoquelaslistasdeadyacenciarepresentanlosbordesdeungrfico,
enpseudocdigoquetratamosalamatrizunsurcocomounatributodelagrfica,delmismomodoenquetratamos
elbordeajustadoE.Enpseudocdigo,porlotanto,vamosaverlanotacintalcomoG:Adjoeu.
Lafigura22.1(b)esunarepresentacindelalistadeadyacenciasdelgrficonodirigidoenlaFig.
Ure22.1(a).Deformasimilar,lafigura22.2(b)esunarepresentacindelalistadeadyacenciadela
DirigidoenlaFigura22.2(a).
SiGesungrafodirigido,lasumadelaslongitudesdetodaslaslistasdeadyacenciaesjEj,
Yaqueunbordedelaforma.u/EsrepresentadaporteneraparecenenAdjoeu.SiGes

Pgina12

22.1Representacionesgrficas 591

https://translate.googleusercontent.com/translate_f 7/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Ungrafonodirigido,lasumadelaslongitudesdetodaslaslistasdeadyacenciaes2jEj,yaque
situ/Esunbordenodirigido,entoncesuapareceenlalistadeadyacenciayviceversa.
Paralosgrficosdirigidosynodirigidos,larepresentacindelalistadeadyacenciatienela
Propiedaddeseablequelacantidaddememoriaquerequierees.VCE/.
Podemosadaptarfcilmentelistasdeadyacenciapararepresentargrafosponderados,esdecir,lasgrficas
paraelquecadabordetieneunpesoasociado,porlogeneraldadaporunafuncindeponderacin
WWE!R.Porejemplo,seaGD.V,E/ungrficoponderadoconpeso
Funcinw.Simplementealmacenamoselpesowu/Delborde.u/2Econ
Vrticeenlalistadeadyacenciadeu.Larepresentacindelalistadeadyacenciaesbastante
Quepodemosmodificarloparasoportarmuchasotrasvariantesdelgrfico.
Unadesventajapotencialdelarepresentacindelalistadeadyacenciaesqueproporciona
Nohaymaneramsrpidadedeterminarsiunbordedado.u/Estpresenteenelgrfico
queabuscarenlalistadeadyacenciaAdjoeu.Unamatrizdeadyacenciarepresenta
Cindelgrficoremediaestadesventaja,peroacostadeutilizarasintticamente
Msmemoria.(Verelejercicio22.18parasugerenciasdevariacionesenlaslistasdeadyacencia
Quepermitenunabsquedamsrpidadelborde.)
ParalarepresentacindematrizdeadyacenciadeunagrficaGD.VE/,suponemos
Quelosvrticesestnnumerados12Deunamaneraarbitraria.Entoncesel
LarepresentacindematrizdeadyacenciadeungrafoGconstadeunamatrizjVjjVj
IjAD.a/talque
(
1si.ij/2E
aijD
0encasocontrario:
Lasfiguras22.1(c)y22.2(c)sonlasmatricesdeadyacenciadelasmatricesnodirigidasydi
EnlasFiguras22.1(a)y22.2(a),respectivamente.Lamatrizdeadyacenciade
ungrficoquerequiere,.V2/memoria,independientedelnmerodearistasenelgrfico.
ObservelasimetraalolargodeladiagonalprincipaldelamatrizdeadyacenciaenlaFig
Ure22.1(c).Puestoqueenungrficonodirigido,.u/Y.Ereselmismo
borde,lamatrizdeadyacenciaAdeungrafonodirigidoessupropiatranspuesta:ADAT.
Enalgunasaplicaciones,valelapenaalmacenarslolasentradassobreyporencimadeladiagonalde
Lamatrizdeadyacencia,cortandoaslamemorianecesariaparaalmacenarelgrficocasi
alamitad.
Aligualquelarepresentacinenunalistadeadyacenciasdeungrfico,unamatrizdeadyacenciapuederepresentar
Enviungrficoponderado.Porejemplo,siGD.VE/esungrficoponderadoconelborde
Funcindelpesow,podemosalmacenarsimplementeelwudelpeso/Delborde.u2
Comolaentradaenlafilauylacolumnadelamatrizdeadyacencia.Siunaaristano
existir,podemosalmacenarunvalorNILcomosuentradadelamatrizcorrespondiente,aunqueparamuchos
Problemasesconvenienteutilizarunvalorcomo0o1.
Aunquelarepresentacindelalistadeadyacenciaesasintticamentealmenoscomoespacio
Eficientescomolarepresentacindelamatrizdeadyacencia,lasmatricesdeadyacenciasonmssimples,
Yaspodemospreferirlascuandolasgrficassonrazonablementepequeas.Porotraparte,adja

Pgina13

592 Captulo22Algoritmosdegrficoselementales

Lasmatricesdealtadensidadtienenunaventajaadicionalparalosgrficosno
Unbitporentrada.

Representacindeatributos

Lamayoradelosalgoritmosqueoperanengrficosnecesitanmanteneratributosparalosvrtices
Y/obordes.Indicamosestosatributosutilizandolanotacinhabitual,talescomo:d
Paraunatributoddeunvrtice.Cuandoindicamoslosbordescomoparesdevrtices,
Utilizarelmismoestilodenotacin.Porejemplo,silosbordestienenunatributof,entonces
Denotaresteatributoparaelborde.u/By.u/:F.Conelfindepresentary
Algoritmosdecomprensin,nuestranotacindeatributoessuficiente.
Laimplementacindeatributosdevrticeybordeenprogramasrealespuedeserotrahistoria
enteramente.Nohayunamejormaneradealmacenaryaccederaatributosdevrticeyborde.
Paraunasituacindada,sudecisindependerprobablementedela
Queestutilizando,elalgoritmoqueestimplementando,ycmoelrestodesu
Programautilizaelgrfico.Sirepresentaungrficousandolistasdeadyacencia,undiseo
Representaatributosdevrticeenmatricesadicionales,talescomounamatrizd1::jVjque
esparalelaalamatrizAdj.SilosvrticesadyacentesaUestnenAdjoeu,entoncesloquellamamos
elatributou:drealmentesealmacenaenlaentradadelamatrizdu.Muchasotrasmaneras
Delosatributosdeimplementacinsonposibles.Porejemplo,enunprogramaorientadoaobjetos
Lenguajedeprogramacin,losatributosdevrticepuedenrepresentarsecomovariablesdeinstancia
DentrodeunasubclasedeunaclaseVertex.

Ceremonias

22.11
Dadaunarepresentacindelalistadeadyacenciasdeungrficodirigido,cuntotiempotoma
Paracalcularelgradodesalidadecadavrtice?Cuntotiemposetardaencomputarel
Engrados

22.12
https://translate.googleusercontent.com/translate_f 8/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Proporcioneunarepresentacindelistadeadyacenciaparaunrbolbinariocompletoen7vrtices.Dar
Unarepresentacinequivalentedematrizdeadyacencia.Supongamosquelosvrticesestnnumerados
De1a7comoenunmontnbinario.

22,13
LatranspuestadeungrafodirigidoGD.VE/GeselgrafoT.VDET/,donde
ETDf.U/2V VW.u/2Eg.Porlotanto,GTesGcontodossusbordesinvertidos.
DescribiralgoritmoseficientesparaelclculodeGTdeG,tantoparaeladjacency
ListaylasrepresentacionesdematrizdeadyacenciadeG.Analizarlostiemposdeejecucindesu
Algoritmos

Pgina14

22.1Representacionesgrficas 593

22,14
DadaunarepresentacindelistadeadyacenciadeunmultigrafaGD.VE/,describiruna
OVCE/timealgoritmoparacalcularlarepresentacindelalistadeadyacenciadela
"Equivalente"grafonodirigidoG0D.VE0/,dondeE0secomponedelosbordesenE
Contodoslosbordesmltiplesentredosvrticesreemplazadosporunsolobordeycontodos
Autobucleseliminados.

22,15
ElcuadradodeungrafodirigidoGD.VE/Geselgrfico2D.VE2/talque
.u/2E2Gsiyslocontieneunarutaconunmximodedosbordesentreuy.
DescribiralgoritmoseficientesparaelclculodeG2deG,tantoparaeladjacency
ListaylasrepresentacionesdematrizdeadyacenciadeG.Analizarlostiemposdeejecucindesu
Algoritmos

22.16
Lamayoradelosalgoritmosdegrficosquetomanunarepresentacindematrizdeadyacenciacomoentradare
cuadernillotiempo.V2/,perohayalgunasexcepciones.Muestracmodeterminarsi
ungrafodirigidoGcontieneunlavabouniversal,unvrticecongradodeentradajVj1y
Outdegree0entiempoOV/,dadaunamatrizdeadyacenciaparaG.

22,17
LamatrizdeincidenciadeungrafodirigidoGD.VE/sinlibrebuclesesuna
Un
jVjjejmatrizBD.b ij/talque

1sielbordejdejaelvrticei
bijD 1 Sielbordejentraenelvrticei
0 Delocontrario:

DescribenloquelasentradasdelamatrizproductoBBTrepresentan,dondeBTesla
TransponerdeB.

22,18
Supongamosqueenlugardeunalistaenlazada,cadaentradadelamatrizAdjoeuesunacontencintablahash
Losvrticesparaloscuales.u/2E.Sitodaslasbsquedasdebordesonigualmenteprobables,
Eseltiempoesperadoparadeterminarsiunbordeestenelgrfico?Qudesventaja
Qutieneesteesquema?Sugerirunaestructuradedatosalternativaparacadalistadeborde
Quesolucionaestosproblemas.Sualternativatienedesventajasencomparacincon
Lamesahash

Pgina15

594 Captulo22Algoritmosdegrficoselementales

22.2Breadthprimerabsqueda

Amplitudprimerabsquedaesunodelosalgoritmosmssimplesparalabsquedadeungrficoy
Elarquetipodemuchosalgoritmosgrficosimportantes.Prim'smnimospanning
rbolalgoritmo(Seccin23.2)yDijkstradeunsolofuentedeloscaminosmscortosalgoritmo
(Seccin24.3)usanideassimilaresalasdebsquedadeamplitud.
DadaunagrficaGD.VE/yunafuentevrticedistinguidos,primeroenamplitud
LabsquedaexplorasistemticamentelosbordesdeGpara"descubrir"cadavrticequees
Accesibledesdes.Calculaladistancia(elnmeromspequeodebordes)des
Acadavrticealcanzable.Tambinproduceun"rboldeanchoprimer"conrazsque
https://translate.googleusercontent.com/translate_f 9/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Contienetodoslosvrticesalcanzables.Paracualquiervrticeaccesibledesdes,elcaminosimple
Enelrboldeanchoprimerodesacorrespondeaun"caminomscorto"desa
EnG,esdecir,unatrayectoriaquecontieneelnmeromspequeodebordes.Elalgoritmofunciona
Engrficosdirigidosynodirigidos.
Laprimerabsquedasedenominaporqueamplalafronteraentreladiscusin
Uniformementeatravsdelaanchuradelafrontera.Ese
Es,elalgoritmodescubretodoslosvrticesaladistanciakdesantesdedescubrircualquier
VrticesaladistanciakC1.
Pararealizarunseguimientodelprogreso,labsquedaenlaanchuradelabsquedacoloreacadavrticeblanco,griso
negro.Todoslosvrticescomienzanenblancoypuedenllegarasermstardegrisyluegonegro.UN
vrticesedescubrilaprimeravezqueseencuentradurantelabsqueda,encuyomomento
Seconvierteennoblanco.Porlotanto,sehandescubiertovrticesgrisesynegros,pero
Enprimerlugar,labsquedadistingueentreellosparaasegurarquelabsquedaprocede
Enunamaneraanchaprimera. Situ/2Eyelvrticeuesnegro,entonceselvrtice
1

EsgrisonegroEsdecir,todoslosvrticesadyacentesavrticesnegroshansido
descubierto.Losvrticesgrisespuedenteneralgunosvrticesblancosadyacentesellosrepresentan
Lafronteraentrevrticesdescubiertosynodescubiertos.
Breadthfirstsearchconstruyeunprimerrboldeancho,inicialmenteconteniendosolamentesu
Raz,queeselvrticefuentes.Siemprequelabsquedadescubreunvrticeblanco
Enelcursodelaexploracindelalistadeadyacenciadeunvrticeudescubierto,el
Vrticeyelborde.u/Seagreganalrbol.Decimosqueueselpredecesor
oelpadreenelrboldeprimeroenamplitud.Dadoqueunvrticesedescubrecomomuchounavez,
Tienecomomximounodelospadres.Relacionesdeantepasadosydescendientesenlaamplitud
rbolsedefinenconrespectoalarazscomodecostumbre:siuestenlarutasimpleenelrbol
Desdelarazshastaelvrtice,entoncesuesunantepasadodeyesundescendientedeu.

1Sedistingueentrevrticesgrisynegroparaayudaraentendercmoopcindebsquedaprimeroenamplitud
Ciones.Dehecho,comomuestraelejercicio22.23,obtendramoselmismoresultadoinclusosinodistinguimos
Entrevrticesgrisesynegros.

Pgina16

22.2Breadthprimerabsqueda 595

ElprocedimientodebsquedadeamplitudBFSacontinuacinpresuponequeelgrficodeentrada
GD.VE/serepresentausandolistasdeadyacencia.Conectavarios
Atributosacadavrticedelagrfica.Almacenamoselcolordecadavrticeu2V
enelatributou:elcoloryelpredecesordeuenelatributou:.Sinotienes
predecesor(porejemplo,siudsounohasidodescubierto),entoncesu:DNIL.
Elatributou:dmantieneladistanciadelafuentesdevrticeucalculadaporel
algoritmo.ElalgoritmotambinutilizaunacoladeentradaprimeroprimeroQ(vaselaSeccin10.1)
Paragestionarelconjuntodevrticesgrises.

BFS.GS
1paracadavrticeu2G:VFSG
2 u:DColorBLANCO
3 u:Dd1
4 u:DNIL
5s:DColorGRIS
6s:Dd0
7s:DNIL
8QD
9ENQUEUE.QS
10,mientrasqueQ
11 uDDEQUEUE.Q/
12 porcada2G:Adjoeu
13 si:elcolorBLANCO==
14 :DColorGRIS
15 :Ddu:dC1
diecisis Du
17 ENQUEUE.Q/
18 u:DColorNEGRO

Lafigura22.3ilustraelprogresodeBFSenungrficodemuestra.
ElprocedimientoBFSfuncionacomosigue.Conlaexcepcindelvrticefuentes,
lneas14pintarcadavrticeblanco,conjuntoU:dserinfinitoparacadavrticeu,yestablecer
lospadresdecadavrticeesnulo.Lalnea5pintasgris,yaqueconsideramosquees
Descubiertoamedidaqueseiniciaelprocedimiento.Lnea6:inicializasda0,ylalnea7establecela
predecesoradelafuenteesnulo.Laslneas89inicializanQalacolaquecontiene
Sloelvrtices.
Elbuclewhiledelaslneas1018iteraeltiempoquequedanvrticesgrises,
Quesonvrticesdescubiertosqueannohantenidosuslistasdeadyacenciatotalmenteex
AminadoEstebuclemientrasmantieneinvariablelasiguiente:

Enlapruebaenlalnea10,lacolaQconsisteenelconjuntodevrticesgrises.

https://translate.googleusercontent.com/translate_f 10/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina17

596 Captulo22Algoritmosdegrficoselementales

R S T Usted R S T Usted
0 1 0
(un) Q S (segundo) Q W R
0 1 1 1
V W x Y V W x Y
R S T Usted R S T Usted
1 0 2 1 0 2
(do) Q R T x (re) Q T x V
1 2 1 2 2 2 1 2 2 2 2
V W x Y V W x Y
R S T Usted R S T Usted
1 0 2 3 1 0 2 3
(mi) Q x V Usted (F) Q V Usted
Y
2 1 2 2 2 3 2 1 2 3 2 3 3
V W x Y V W x Y
R S T Usted R S T Usted
1 0 2 3 1 0 2 3
(gramo) Q Usted
Y (marido) Q Y
2 1 2 3 3 3 2 1 2 3 3
V W x Y V W x Y
R S T Usted
1 0 2 3
(yo) Q
2 1 2 3
V W x Y

Figura22.3LaoperacindeBFSenungrafonodirigido.Losbordesdelrbolsemuestransombreados
SonproducidosporBFS.Elvalordeu:daparecedentrodecadavrticeu.LacolaQsemuestraenla
comienzodecadaiteracindelbuclewhiledelaslneas1018.Lasdistanciasdevrticeaparecendebajodelosvrtices
enlacola.

Aunquenovamosautilizarestebucleinvarianteparaprobarlacorreccin,esfcildever
Quemantieneantesdelaprimeraiteracinyquecadaiteracindellazomantiene
Elinvariante.Antesdelaprimeraiteracin,elnicovrticegrisyelnicovrtice
EnQ,eselvrticefuentes.Lalnea11determinaelvrticegrisuenlacabezade
lacolaQyloeliminadeP.Elbucledelaslneas1217consideracada
Vrticeenlalistadeadyacenciadeu.Siesblanco,entoncesannosehadescubierto,
Yelprocedimientolodescubreejecutandolaslneas1417.Elprocedimientopinta
vrticegris,establecesudistancia:dparau:dC1,registrosucomosupadre:ylugares
QueenlacoladelacolaQ.Unavezqueelprocedimientohaexaminadotodoslosvrticesenu

Pgina18

22.2Breadthprimerabsqueda 597

Adyacente,ennegreceuenlalnea18.Elinvariantedellazosemantieneporque
Cadavezqueunvrticesepintadecolorgris(enlalnea14)tambinseponeencola(enlalnea17),y
Cadavezqueunvrticesedeshace(enlalnea11)tambinsepintaennegro(enlalnea18).
Losresultadosdelabsquedadeamplitudpuedendependerdelordenenquelosvecinos
Borsdeunvrticedadosevisitanenlalnea12:elrboldeanchoprimerpuedevariar,peroel
ddistanciascalculadasporelalgoritmonolohar.(Vaseelejercicio22,25).

Anlisis
Antesdeprobarlasdiversaspropiedadesdebsquedaenanchura,asumimoslaalguien
lomsfcileltrabajodeanlisisdesutiempoqueseejecutaenungrficodeentradaGD.VE/.Nosotros
utilizarelanlisisagregado,comovimosenlaseccin17.1.Despusdelainicializacin,primeroenamplitud
bsquedasinblanqueaunvrtice,yporlotantolapruebaenlalnea13seaseguradequecadavrtice
esencoladoalosumounavez,yporlotantoquitadodelacolacomomximounavez.Lasoperacionesde
enqueuingydesencolatomaO.1/hora,porloqueeltiempototaldedicadoalacola
operacionesesOV/.Debidoaqueelprocedimientoexploralalistadeadyacenciadecadavrtice
slocuandosequitadelacoladelvrtice,queescaneacadalistadeadyacenciacomomximounavez.Yaque
lasumadelaslongitudesdetodaslaslistasdeadyacenciaes,.E/,eltiempototalempleadoen
listasdeadyacenciadeexploracinesOE/.LasobrecargadeinicializacinesOV/,y
portanto,eltiempototaldeejecucindelprocedimientoBFSesOVCE/.Porlotanto,primeroenamplitud
bsquedaseejecutaentiempolinealeneltamaodelarepresentacindeadyacencialistadeG.

https://translate.googleusercontent.com/translate_f 11/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
caminosmscortos
Alcomienzodeestaseccin,seafirmquelabsquedaenamplitudencuentraeldisplay
tanciaacadavrticepuedellegarenunagrficaGD.VE/desdeunvrticefuentedada
s2V.Definirlasdistanciasrutamscorta.s/Sapartirdequeelmeromnimo
BERdearistasencualquiertrayectoriadesdeelvrticealvrticesSinohaycaminodesa,
entonceses/D1.Llamamosauncaminode.slongitud/Sapartirdeunarutamscorta2
desa.Antesdemostrarquelabsquedaenamplitudcalculacorrectamenteshortest
distanciasderuta,queinvestiganunaimportantepropiedaddelasdistanciasdelarutamscorta.

2Enloscaptulos24y25,vamosageneralizarnuestroestudiodeloscaminosmscortosparagrafosponderados,enlaque
cadabordetieneunpesodevalorrealyelpesodeuncaminoeslasumadelospesosdesucon
bordesconstituyentes.Losgrficosconsideradosenelpresentecaptulonosonponderadoso,equivalentemente,todo
tienenbordesunidaddepeso.

Pgina19

598 Captulo22deprimariaGrficoAlgoritmos

lema22.1
DejeGD.VE/ungrafodirigidoonodirigido,ydejarques2Vunarbitraria
vrtice.Entonces,paracualquier.Uborde/2E,
es.s/au/C1:

PruebaSiuesaccesibledesdes,entoncestambinloes.Enestecaso,larutamscortadesdes
anopuedesermslargoqueelcaminomscortodesdesauseguidodela.Uborde/,
yporlotantoladesigualdadsecumple.Siunoesaccesibledesdes,entonces.su/D1,y
ladesigualdadsecumple.

QueremosdemostrarqueBFSadecuadamentecalcula:d.sD/Paracadaversin
tex2V.Primerodemostramosque:dlmites.s/desdearriba.

lema22.2
DejeGD.VE/ungrafodirigidoonodirigido,ysupongamosqueseejecutaBFS
enGdeunafuentevrticedados2V.Luego,alterminar,paracadaversin
tex2V,elvalor:DcalculasatisfaceBFS:d es/.

PruebaUtilizamosinduccinsobreelnmerodeENQUEUEoperaciones.nuestrainductiva
hiptesisesque:d es/2Vparatodos.
Labasedelainduccineslasituacininmediatamentedespusdeenqueuingsenlalnea9
deBFS.Lahiptesisdeinduccinvlidaenestecaso,yaques:d.sD0Ds/y
:D.sD1/2Vparatodos FSG.
Paralaetapainductiva,considereunvrticeblancoquesedescubreduranteel
buscardesdeunvrticeu.Lahiptesisdeinduccinimplicaqueu:d esu/.De
laasignacinrealizadaporlalnea15ydelLema22.1,obtenemos
:DDT:dC1
esu/C1
es/:
VrticeAcontinuacin,seponeencola,ynuncaseponeencoladenuevo,yaquetambinestengris
ylacontinuacinclusuladelaslneas1417seejecutasloparablancosvrtices.Porlotanto,la
valorde:dnuncacambiadenuevo,ysemantienelahiptesisinductiva.

Paraprobarque:d.sD/,TenemosquedemostrarprimeroconmayorprecisincmolacolaQ
operaeneltranscursodeBFS.Elsiguientelemamuestraqueentodomomento,el
colacontienecomomximodosdvaloresdistintos.

Pgina20

22.2primeroenamplituddebsqueda 599

lema22.3
SupongamosquedurantelaejecucindeBFSenungrficoGD.VE/,lacolaQ
contienelosvrticesh12:::ri,donde1eseljefedeQyReslacola.
https://translate.googleusercontent.com/translate_f 12/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Entonces,r:d1:dCy1i:dIC1:ddeiD12:::r1.

PruebaLapruebaesporinduccinsobreelnmerodeoperacionesdelacola.Inicialmente,
cuandolacolacontieneslos,ellemadudatiene.
Paralaetapainductiva,hayquedemostrarqueellemamantienedespusdequeambosdesencola
yenqueuingunvrtice.Silacabeza1delacolasequitadelacola,2seconvierteenel
nuevacabeza.(Silacolasevaca,ellemasostienevacuamente.)Porel
hiptesisdeinduccin,1:d2:d.Peroentoncestenemosr:d1:dC12:dC1,
ylasdesigualdadesquequedanactivas.Porlotanto,ellemasiguecon2como
lacabeza.
Conelfindeentenderloquesucedeenenqueuingunvrtice,necesitamosex
aminaelcdigomsdecerca.CuandoEnqueueunvrticeenlalnea17deBFS,se
seconvierteenRC1.Enesemomento,yahemoseliminadovrticeu,cuyaadyacencia
ListaActualmenteestsiendoescaneado,delacolaQ,yporlahiptesisdeinduccin,
elnuevojefe1tiene1:d u:d.Porlotanto,RC1:dD:DDT:dC11:dC1.De
lahiptesisdeinduccin,tambintenemosr:dUnU:dC1,yasr:dUnU:DCD1
:DDRC1:d,ylasdesigualdadesquequedanactivas.Porlotanto,ellema
delasiguientemaneracuandoestencola.

Elsiguientecorolariomuestraquelosvaloresdedenelmomentoenquelosvrticesson
enqueuedestnaumentandomontonamenteconeltiempo.

corolario22.4
SupongamosquelosvrticesiyjestnencoladurantelaejecucindeBFS,y
queiesencoladoantesj.Entoncesi:dj:denelmomentoenquejesencolado.

LapruebainmediatadelLema22.3ylapropiedaddequecadavrticerecibeuna
valordfinitoalosumounavezduranteelcursodeBFS.

Ahorapodemosprobarquelabsquedaenamplitudencuentracorrectamentelarutamscortadis
distancias.

Teorema22.5(Correccindelabsquedaenamplitud)
DejeGD.VE/ungrafodirigidoonodirigido,ysupongamosqueseejecutaBFS
enGdeunafuentevrticedados2V.Luego,durantesuejecucin,descubreBFS
cadavrtice 2Vqueesaccesibledesdelafuentes,yunavezterminado,
:DD.s/paratodos 2V.Adems,paracualquiervrtice squeesalcanzable

Pgina21

600 Captulo22deprimariaGrficoAlgoritmos

des,unadelasrutasmscortasdesdesa Esuncaminomscortodesdesa:
seguidoporelborde.:/.

PruebaSupongamos,porelpropsitodelacontradiccin,quealgunosvrticerecibead
elvalornoesigualasudistanciadelcaminomscorto.Dejar serelvrticeconmin
.simum/Querecibeunvalordedtalesincorrectaclaramente s.Por
Lema22.2,:D es/,Yastenemosque:d>.s/.Vertexdebeser
accesibledesdes,porquesinoesas,entonces.s/D1:d.Seauelvrticeim
mediatamenteanteriorenuncaminomscortodesa,demodoque.s/D.su/C1.
Porquees</u.s/,Ydebidoalaformaenqueelegimos,tenemosu:d.sDu/.
Poniendoestaspropiedadesjuntas,tenemos
:D>.s/D.sT/C1Du:dC1: (22.1)
ConsideremosahoraelmomentoenqueBFSoptaporquitardelacoladelvrticeuQen
lalnea11.Enestemomento,elvrtice
esblanco,grisonegro.Mostraremos
queencadaunodeestoscasos,sederivaunacontradiccinconladesigualdad(22.1).Sies
blanco,luegolalnea15conjuntos:dDU:dC1,loquecontradiceladesigualdad(22.1).Sies
negro,deloqueyasehaquitadodelacolay,porCorolario22.4,tenemos
:DAU:D,ladesigualdaddenuevoencontradiccincon(22.1).Siesdecolorgris,despussepint
grissobredesencolaalgnvrticew,quefueretiradodeQantesdeu
yparalacual:DDw:dC1.PorCorolario22.4,sinembargo,w:dUnU:D,porloque
tiene:dDw:dC1AU:dC1,ladesigualdad,unavezmsencontradiccincon(22.1).
Porlotantoseconcluyeque:d.sD/paratodos 2V.Todoslosvrticesalcanzables
desdebeserdescubierto,puesdelocontrariotendranque1D:d>.s/.A
laconclusindelapruebadelteorema,observarquesi:Du,entonces:dDu:dC1.
Deestemodo,podemosobtenerunarutamscortadesparatomandounarutamscortades
a:ydespusdeatravesarelborde.:/.

rbolesenamplitud
ElprocedimientoBFSconstruyeunrbolenanchura,yaquebuscaenelgrfico,comoFi
Ure22.3ilustra.Elrbolcorrespondeala AtributosMsformalmente,por
unagrficaGD.VE/sconlafuente,quedefinenelsubgrafoantecesordelGcomo

https://translate.googleusercontent.com/translate_f 13/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
GD.VE/,donde
FVD2VW:NILg[FSG
y
EDf.:/W2V FSGG:
ElpredecesorsubgrafoGesunrbolenamplitudsiVestformadoporlosvrtices
accesibledesdesy,apesarde2V,elsubgrafoGcontieneunsimplenico

Pgina22

22.2primeroenamplituddebsqueda 601

caminodesaquetambinesuncaminomscortodesdesenG.Unrbolenamplitud
esdehechounrbol,yaqueestconectadoyJEjDjVj1(verTeoremaB.2).Nosotros
llamaralosbordesdeEbordesdelosrboles.
ElsiguientelemamuestraqueelsubgrafoprecursorproducidoporlaBFS
procedimientoesunrbolenamplitud.

lema22.6
CuandoseaplicaaungrafodirigidoonodirigidoGD.VE/,BFSprocedimientocon
estructurasparaqueelsubgrafopredecesorGD.VE/esunrbolenamplitud.

PruebaLnea16deBFSestablece:Dusiyslosi.u/2Ey.s/<1
esdecir,siesaccesibledesdesVyporlotantosecomponedelosvrticesenValcanzable
dels.PuestoqueGformaunrbol,porB.2teorema,quecontieneuncaminosimplenico
desacadavrticeenV.Aplicandoelteorema22.5inductivamente,llegamosalaconclusin
quecadaunodetalescaminoesuncaminomscortoenG.

Lassiguientesimpresionesdevisitantelosvrticesdeuncaminomscortodesdesa,
suponiendoqueBFSyahacalculadounrbolenamplitud:

PRINTPATH.Gs/
1si==s
2 sdeimpresin
3elseif:==NIL
4 imprimir"hayuncaminode"s"a""existe"
5personaPRINTPATH.Gs:/
6 impresin

Esteprocedimientoseejecutaentiempolinealenelnmerodevrticesenelcaminoimpresos,
puestoquecadallamadarecursivaesparaunarutadeunvrticemscorto.

Ceremonias

22,21
Mostrareldy losvaloresqueresultandeejecutarlabsquedaenamplitudenladi
grficorecteddelafigura22.2(a),conelvrtice3comolafuente.

22,22
MostrarelDylosvaloresquedanlugaralaejecucindebsquedaenamplitudenelindiviso
grficorecteddelafigura22.3,conelvrticeucomolafuente.

Pgina23

602 Captulo22deprimariaGrficoAlgoritmos

22,23
Muestranqueelusodeunsolobitparaalmacenarcadacolordevrticebastaconelargumentodequela
BFSprocedimientoproduciraelmismoresultadosiseeliminaranlaslneas5y14.

22,24
CuleseltiempodeejecucindeBFSsirepresentamoselgrficodeentradaporunaadyacencia
Matrixymodificarelalgoritmoparamanejarestetipodeentrada?

22,25
Argumentanqueenunabsquedaenamplitud,elvalorU:Dasignadoaunvrticeuesinde
pendientedelaordenenelqueaparecenlosvrticesencadalistadeadyacencia.Utilizando
Figura22.3comounejemplo,muestranqueelrbolprimeroenamplitudcalculadaporBFSpuede
dependerdelaordenacindentrodelaslistasdeadyacencia.

22,26
https://translate.googleusercontent.com/translate_f 14/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
DunejemplodeungrafodirigidoGD.VE/,unvrticefuentes2V,yuna
conjuntoderboldebordesEAEtalqueparacadavrtice2V,elnicocaminosimple
enel.VgrficoE/sdequeesuncaminomscortoenG,sinembargo,elconjuntodearistasE
nopuedeserproducidomediantelaejecucindeBFSenG,noimportacmoseordenanlosvrtices
encadalistadeadyacencia.

22,27
Haydostiposdeluchadoresprofesionales:"babyfaces"("buenos")y
"talones"("malos").Entrecualquierpardeluchadoresprofesionales,nopuedeo
puedequenoseaunarivalidad.Supongamosquetenemosnluchadoresprofesionalesytenemosunalista
rdeparesdeluchadoresparaelquehayrivalidades.PordarunaCr/tiempoalgo
rithmquedeterminasiesposibledesignaraalgunosdelosluchadorescomo
babyfacesyelrestocomotalonesdemaneraquecadarivalidadesentreunbabyface
yuntaln.Siesposiblerealizartaldesignacin,elalgoritmodebe
producirlo.

22,28?
EldimetrodeunrbolTD.VE/sedefinecomounmximodeu2V.u/,esoesel
msgrandedetodaslasdistanciasdelarutamscortaenelrbol.Dunalgoritmoeficientepara
calculareldimetrodeunrbol,yanalizareltiempodefuncionamientodesualgoritmo.

22,29
DejeGD.VE/unagrficaconexanodirigida.DunCEOV/tiempoalgo
rithmparacalcularunarutaenGqueatraviesacadaaristaenEexactamenteunavezencada
direccin.Describecmopuedesencontrarlasalidadeunlaberintosiseledauna
grancantidaddemonedasdeuncentavo.

Pgina24

22.3Profundidadprimerabsqueda 603

22.3Profundidadprimerabsqueda

Laestrategiaseguidaporlabsquedaenprofundidades,comosunombreloindica,alabsqueda
"Profundo"enelgrficosiemprequeseaposible.Profundidadprimerabsquedaexplorabordescabo
delvrticemsrecientementedescubiertoquetodavatienebordesinexploradassalirdeella.
Unavezquetodos'sbordeshansidoexplorados,labsquedade"marchaatrs"paraexplorarlosbordes
dejandoelvrticedelaquefuedescubierto.Esteprocesocontinahastaque
handescubiertotodoslosvrticesquesonaccesiblesdesdeelvrticefuenteoriginal.
Sialgnvrticenodescubiertossiguensiendo,acontinuacin,labsquedaprimeroenprofundidadseleccionaunodeelloscomo
unanuevafuente,yserepitelabsquedadeesafuente.Elalgoritmorepiteeste
todoelprocesohastaquesehayadescubiertocadavrtice.3
Aligualqueenlabsquedaenamplitud,cadavezquelabsquedaenprofundidaddurantedescubreunvrtice
ingunaexploracindelalistadeadyacenciadeunvrticeyadescubiertasu,seregistraesta
eventoalconfigurarun'spredecesordeatributos:au.Adiferenciadelabsquedaenamplitud,
cuyasubgrafopredecesorformaunrbol,elsubgrafoprecursorproducidopor
unabsquedaenprofundidadpuedeestarcompuestodevariosrboles,yaquelabsquedapuede
repetirdesdemltiplesfuentes.Porlotanto,sedefineelsubgrafopredecesorde
unabsquedaenprofundidaddeformaligeramentediferentedeladeunabsquedaenanchura:dejamos
GD.VE/,donde
EDf.:/W2Vy:NILg:
Elpredecesordeunsubgrafobsquedaenprofundidadformaunbosqueprimeroenprofundidadcom
comprendevariosrbolesprimeroenprofundidad.LosbordesenEsonlosbordesdelosrboles.
Aligualqueenlabsquedaenamplitud,profundidadprimerabsquedavrticescoloresdurantelabsquedade
indicarsuestado.Cadavrticeesinicialmenteblanco,apareceengriscuandosedescubri
enlabsqueda,yestennegrecidocuandosetermin,esdecir,cuandosulistadeadyacencia
hasidoexaminadoporcompleto.Estatcnicagarantizaquecadavrticetermina
exactamenteenunrboldeprimeroenprofundidad,porloqueestosrbolessondisjuntos.
Ademsdecrearunbosqueprimeroenprofundidad,bsquedaenprofundidadtambinlasmarcasdetiempocadaversin
Texas.Cadavrticetienedosmarcasdetiempo:laprimeramarcadetiempo:dregistroscuando
sedescubriporprimeravez(ygris),ylasegundamarcadetiempo:fregistroscuandoel
Bsquedaterminedeexaminarlo'slistadeadyacencia(yennegrece).estasmarcasdetiempo

3Puedeparecerarbitrarioquelabsquedaenamplitudselimitaaunasolafuente,mientrasqueporprofundidad
bsquedapuedebuscardesdemltiplesfuentes.Aunqueconceptualmente,bsquedaenamplitudpodraproceder
apartirdemltiplesfuentesybsquedaenprofundidadpodralimitarseaunasolafuente,nuestroenfoquereflejacmo
losresultadosdeestasbsquedasseutilizannormalmente.Primeroenamplituddebsquedaporlogeneralsirveparaencontrarshortest
distanciasdetrayectoria(yelsubgrafopredecesorasociado)deunafuentedeterminada.Labsquedaenprofundidades
menudounasubrutinaenotroalgoritmo,comoveremosmsadelanteenestecaptulo.

https://translate.googleusercontent.com/translate_f 15/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Pgina25

604 Captulo22deprimariaGrficoAlgoritmos

proporcionarinformacinimportanteacercadelaestructuradelagrficaysongeneralmente
tilesenelrazonamientosobreelcomportamientodebsquedaenprofundidad.
ElprocedimientoDFSdebajoregistroscuandodescubrevrticeuenelatributou:D
ycuandotermineuvrticeenelatributou:f.Estasmarcasdetiemposonnmerosenteros
entre1y2jVj,puestoquehayuneventodescubrimientoyuneventodeacabadopara
cadaunodelosvrticesjJV.Porcadauvrtice,
u:d<u:f: (22.2)
VrticeuesBLANCOantesdelahorau:d,GRISentreeltiempou:Dylahorau:f,y
NEGROpartirdeentonces.
Elsiguientepseudocdigoeselalgoritmobsicodeprofundidadprimerabsqueda.Laentrada
grafoGpuedenodirigidoodirigido.Lavariabletiempoesunavariableglobalque
queutilizamosparaselladodetiempo.

DFS.G/
1decadavrticeu2G:V
2 u:elcolorDBLANCO
3 u:DNIL
4tiempoD0
5paracadavrticeu2G:V
6 siu:elcolor==BLANCO
7 DFSVISIT.Gu/

DFSVISIT.Gu/
1horaDtiempodeC1 //Vrticeblancouacabadeserdescubierto
2u:DDtiempo
3u:elcolorDGRIS
4decada2G:Adjoeu //Explorar.uborde/
5 si:elcolor==BLANCO
6 :Du
7 DFSVISIT.G/
8u:elcolorDNEGRO //Ennegreceruestaterminado
9tiempoDtiempodeC1
:10UfDtiempo

Lafigura22.4ilustraelprogresodelaDFSenelgrficoquesemuestraenlafigura22.2.
ProcedimientoDFSfuncionacomosigue.Lneas13pintantodoslosvrticesblancoytiva
Darformatoasu
atribuyeaNIL.Lnea4reiniciaelcontadordetiempoglobal.Laslneas57
comprobarcadavrticeenVasuvezy,cuandoseencuentraunvrticedelproducto,visiteusando
DFSVISIT.CadavezDFSVISIT.Gu/sellamaenlalnea7,seconvierteenelvrticeu

Pgina26

22.3Profundidadprimerabsqueda 605

Usted V W Usted V W Usted V W Usted V W


1/ 1/ 2 1/ 2 1/ 2

3/ 4/ 3/
x Y Z x Y Z x Y Z x Y Z
(un) (segundo) (do) (re)
Usted V W Usted V W Usted V W Usted V W
1/ 2 1/ 2 1/ 2 1/ 2/7
segundo segundo segundo segundo
4/ 3/ 4/5 3/ 4/5 3/6 4/5 3/6
x Y Z x Y Z x Y Z x Y Z
(mi) (F) (gramo) (marido)
Usted V W Usted V W Usted V W Usted V W
1/ 2/7 1/8 2/7 1/8 2/7 9/ 1/8 2/7 9/
F segundo F segundo F segundo F segundo do
4/5 3/6 4/5 3/6 4/5 3/6 4/5 3/6
x Y Z x Y Z x Y Z x Y Z
(yo) (J) (K) (L)
Usted V W Usted V W Usted V W Usted V W
1/8 2/7 9/ 1/8 2/7 9/ 1/8 2/7 9/ 1/8 2/7 9/12
F segundodo F segundodo F segundo do F segundodo
segundo segundo segundo
4/5 3/6 10/ 4/5 3/6 10/ 4/5 3/6 10/11 4/5 3/6 10/11
x Y Z x Y Z x Y Z x Y Z
(metro) (norte) (O) (pag)

Figura22.4ElprogresodelalgoritmodeprofundidadprimerobsquedaDFSenungrficodirigido.comobordes

https://translate.googleusercontent.com/translate_f 16/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
sonexploradosporelalgoritmo,quesemuestrancomoseasombreada(sisonbordesderboles)oestrellados
(deotramanera).NontreebordesestnetiquetadosB,CoFdeacuerdoasiestndevuelta,cruz,o
bordesdelanteros.Lasmarcasdetiempodentrodelosvrticesindicaneltiempodedescubrimiento/tiemposdeacabado.

larazdeunnuevorbolenelbosqueprimeroenprofundidad.CuandoregresaDFS,cadavrticeu
selehaasignadountiempodedescubrimientou:Dyunahoradefinalizacinu:f.
EncadallamadaDFSVISIT.Gu/,vrticeuesinicialmenteblanco.Lneaincrementosde1
lavariableglobaltiempo,lalnea2registraelvalornuevodetiempocomoeldescubrimiento
utiempo:d,ylalnea3pinturasugris.Lneas47examinancadavrticeadyacentealU.
ydeformarecursivavisitarsiesblanco.Comocadavrtice 2Adjoeuseconsideraen
lalnea4,sedicequeelborde.u/Esexploradoporlabsquedaenprofundidad.Finalmente,despusde
cadaaristadejandoUhasidoexplorado,lneas810pinturaunegro,incrementodetiempo,
yregistrareltiempodellegadaenu:f.
Tengaencuentaquelosresultadosdebsquedaenprofundidadpuedendependerdelordenenelque
lalnea5deDFSexaminalosvrticesyenelordenenelquelalnea4delDFS
VISITvisitaalosvecinosdeunvrtice.Estasdiferentesrdenesdevisitanotienden

Pgina27

606 Captulo22deprimariaGrficoAlgoritmos

paracausarproblemasenlaprctica,yaqueporlogeneralsepuedeutilizarcualquierresultadodebsquedaenprofundidad
efectivamente,conresultadosesencialmenteequivalentes.
CuleseltiempodeejecucindeDFS?Losbuclesenlaslneas13y57lneasdeDFS
tomartiempo,.V/,exclusivadelahoradeejecutarlasllamadasaDFSVISIT.Comolohicimos
paralabsquedaenamplitud,usamosanlisisagregado.ElprocedimientoDFSVISITes
llamaexactamenteunavezparacadavrticeV2,yaqueelvrticeuenlaqueDFSVISIT
seinvocadebeserblancayloprimeroqueDFSVISIThaceesvrticedepinturaugris.
DuranteunaejecucindeDFSVISIT.G/,Elbucledelaslneas47ejecutajAdjj
veces.Yaque
x
jAdjjD,.E/
2V
elcostototaldelaejecucindelaslneas47delaDFSVISITes,.E/.Eltiempodeejecucinde
porlotanto,DFSes,.VCE/.

Propiedadesdebsquedaenprofundidad
Labsquedaenprofundidadseobtieneinformacinvaliosasobrelaestructuradeungrafo.Por
quizslapropiedadmsbsicadebsquedaenprofundidadesqueelsubpredecesor
grafoGenefecto,formanunbosquederboles,yaquelaestructuradelaprofundidad
primerosrbolesreflejoexactodelaestructuradelasllamadasrecursivasdeDFSVISIT.Esdecir,
uD:siyslosiDFSVISIT.G/Fuellamadoduranteunabsquedadeadude
Listajacency.Adems,elvrticeesundescendientedelvrticeuenelprimeroenprofundidad
bosquesiyslosisedescubreduranteeltiempoenelqueuesgris.
Otrapropiedadimportantedelabsquedaenprofundidadesqueeldescubrimientoyelacabado
vecestienenestructuraparntesis.Sirepresentamoseldescubrimientodeuvrticecon
unparntesisizquierdo".u"yrepresentarasuacabadoporunparntesisderecho"u/",acontinuacin,
lahistoriadelosdescubrimientosyacabadoshaceunaexpresinbienformadoenel
sentidodequelosparntesisestncorrectamenteanidados.Porejemplo,labsquedaenprofundidad
delafigura22.5(a)correspondealaparentizacinmuestraenlaFigura22.5(b).los
siguienteteoremaproporcionaotramaneradecaracterizarlaestructuraparntesis.

Teorema22.7(Parntesisteorema)
Encualquierbsquedaenprofundidaddeungrafo(dirigidoonodirigido)GD.VE/,paracualquier
dosvrticesuy,exactamenteunadelassiguientestrescondicionessetiene:
laoeuintervalos:du:fyOE:d:Fsoncompletamentedisjuntos,yniuni
esundescendientedelaotraenelbosqueprofundidadprimero,
elintervalooeu:du:festcontenidocompletamentedentrodelintervalodeOE:d:F,yu
esundescendientedeenunrboldeprofundidadprimero,o
elintervalo:d:Festtotalmentecontenidadentrodelintervalodeoeu:du:f,y
esundescendientedeuenunrboldeprofundidadprimero.

Pgina28

22.3Profundidadprimerabsqueda 607

Y Z S T
3/6 2/9 1/10 11/16
segundo F
(un) do segundo

https://translate.googleusercontent.com/translate_f 17/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
4/5 do 7/8 do 12/13 do 14/15
x W V Usted

S T

Z V Usted
(segundo) Y W

x
12345678910111213141516
(S(z(y(xx)y)(ww)z)s)(t(vv)(uu)t)

S T
do segundo
F do
Z V Usted
segundo do
(do)
Y W
do

Figura22.5Propiedadesdebsquedaenprofundidad.(a)Elresultadodeunabsquedaenprofundidaddeundirigido
grafico.Losvrticessonsellosdetiempoylostiposdebordeseindicancomoenlafigura22.4.(b)Losintervalosparalas
eltiempodedescubrimientoylahoradefinalizacindecadavrticecorrespondenalaparentizacinmuestra.Cada
rectnguloseextiendeelintervalodadoporeldescubrimientoylostiemposdeacabadodelvrticecorrespondiente.
Slosemuestranlosbordesdelosrboles.Sidosintervalossesolapan,entoncesunoestanidadodentrodelotro,yel
vrticecorrespondientealintervalomspequeoesundescendientedelvrticequecorrespondealamsgrande.
(c)Elgrficodelaparte(a)redibujadocontodoslosbordesdelrbolyhaciaadelantebajandodentrodeunrboldeprimeroen
ytododevueltabordessubiendodesdeundescendientedeunantepasado.
profundidad

Pgina29

608 Captulo22deprimariaGrficoAlgoritmos

PruebaEmpezamosconelcasoenelqueu:d<:d.Consideramosdossubcasos,
enfuncindesi:d<u:fono.Elprimersubcasoseproducecuando:d<u:f,
porloquefuedescubiertomientrasutodavaeragris,loqueimplicaqueesundescendiente
deu.Adems,puestoquefuedescubiertomsrecientementequeu,todasuoutgo
ingbordessonexplorados,y estterminado,antesdequelabsquedadevuelveaFinlandiay
parroquiasu.Enestecaso,porlotanto,elintervalodeOE:d:Festcontenidaenteramentedentrode
elintervalooeu:du:f.Enlaotrasubcaso,u:f<:d,yporladesigualdad(22.2),
u:d<u:f<:d<:fporlotantolosintervalosOEU:du:fyOE:d:Fsondisjuntos.
Debidoaquelosintervalossondisjuntos,nivrticesedescubrimientrasqueelotro
eradecolorgris,yastampocovrticeesundescendientedelaotra.
Elcasoenelque:d<u:dessimilar,conlasfuncionesdeuyhaciaabajoenel
argumentoanterior.

Corolario22.8(delajerarquizacindelosintervalosdedescendientes)
Vrticeesundescendienteadecuadadeuvrticeenelbosqueprimeroenprofundidadparaun(dirigida
onodirigido)grafoGsiyslosiu:d<:d<:f<u:f.

Lapruebainmediatadelteorema22.7.

Elsiguienteteoremadaotracaracterizacinimportantedecuandounvrtice
esundescendientedeotroenelbosqueprimeroenprofundidad.

Teorema22.9(teoremaBlancopath)
Enunbosqueprimeroenprofundidaddeungrafo(dirigidoonodirigido)GD.VE/,vrticees
undescendientedevrticeusiyslosienelmomentou:Dquelabsquedadescubreu,
hayuncaminodeuacompuestoenteramentedevrticesblancos.

Prueba):SiuD,entonceselcaminodeuacontenersimplementevrticeu,queestodava
blancocuandofijamoselvalordeu:d.Ahora,supongamosqueesundescendienteadecuada
deuenelbosqueprimeroenprofundidad.PorCorolario22.8,u:d<:d,ytambinloesenblanco
utiempo:d.Dadoquepuedesercualquierdescendientedeu,todoslosvrticesenlasencillanico
caminodeuaenelbosqueprimeroenprofundidadsondecolorblancoenelinstanteT:d.
(:Supongamosquehayuncaminodevrticesblancosdesdeuhastaenelmomentou:D,pero
noseconviertaenundescendientedeuenelrbolprimeroenprofundidad.Sinprdidadegeneralizacin
dad,sesuponequecadavrticequenoseaalolargodelarutadeaccesoseconvierteenundescendientedeu.
(Delocontrario,dejarserelvrticemscercanodeUalolargodelcaminoquenoseconviertaenunde
scendantdeu.)Seawelpredecesordelasenda,demodoqueWesundescendiente

https://translate.googleusercontent.com/translate_f 18/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
deu(wyupuedeserdehechoelmismovrtice).PorCorolario22.8,w:fAU:f.Ser
causadebeserdescubiertodespusdequeuesdescubierto,peroantesdequeterminew,tenemos
u:d<:d<w:fUA:f.Teorema22.7implicaentoncesqueelintervalodeOE:d:f

Pgina30

22.3Profundidadprimerabsqueda 609

estcontenidocompletamentedentrodelintervalodeoeu:du:f.PorCorolario22.8,debedespus
todoserundescendientedeu.

Clasificacindelosbordes
Otrapropiedadinteresantedebsquedaenprofundidadesquelabsquedasepuedeutilizar
paraclasificarlosbordesdelagrficadeentradaGD.VE/.Eltipodecadabordepuede
proporcionarinformacinimportanteacercadeungrfico.Porejemplo,enlasiguienteseccin,
Veremosqueesungrafodirigidoacclicosiyslosiunaprofundidadprimerarendimientosdebsquedasin
bordes"atrs"(lema22.11).
PodemosdefinircuatrotiposdebordeentrminosdelaselvaprimeroenprofundidadGproducidospor
unabsquedaenprofundidadsobreG:
1.LosbordesdelrbolsonlosbordesdelbosqueGprimeroenprofundidad..uBorde/Esunaventajasielrbol
fuedescubiertoporprimeravezporexplorar.uborde/.
2.Volverbordessonaquellosbordes.u/Conexindeunvrticeuaunantepasadoenuna
primeroenprofundidadrbol.Consideramoslibrebucles,loquepuedeocurrirenlosgrafosdirigidos,a
volvernbordes.
3.Losbordesdelanterossonaquellosbordes.unontree/Conexindeunvrticeuparaunde
scendantenunrbolprimeroenprofundidad.
4.LosbordesdelaCruzsontodoslosotrosbordes.Puedenirentrelosvrticesdelamisma
profundidadprimerorbol,siemprequeunvrticenoesunantepasadodelaotra,opueden
irentrelosvrticesdediferentesrbolesprimeroenprofundidad.
Enlasfiguras22.4y22.5,lasetiquetasdebordeindicanlostiposdeborde.Lafigura22.5(c)muestratambin
cmovolveradibujarelgrficodelaFigura22.5(a)demodoquetodalacabezarbolybordesdelanteros
labajaenunrbolprimeroenprofundidadytodoslosbordesdenuevosuben.Podemosvolveradibujarcualquiergrfico
deestamanera.
ElalgoritmoDFStienesuficienteinformacinparaclasificaralgunosbordes,yaqueencuen
soraellos.Laideaclaveesquecuandoporprimeravezexploraruna.uborde/,Elcolorde
vrticenosdicealgosobreelborde:
1.BLANCOindicaunbordederboles,
2.GRISindicaunbordeposterior,y
3.NEGROindicaunbordedelanteroocruz.

Elprimercasoesinmediatadelaespecificacindelalgoritmo.Paraelsector
Ensegundocaso,observanquelosvrticesgrisessiempreformanunacadenalinealdedescendientes
correspondientealapiladeDFSVactivosISITinvocacioneselnmerodegris
vrticesesunomsdelaprofundidadenelbosqueprimeroenprofundidaddelvrticemsre
recientementedescubierto.Exploracinsiempreprocededelvrticegrisprofundo,porlo

Pgina31

610 Captulo22deprimariaGrficoAlgoritmos

unaventajaquellegaaotrovrticegrishallegadoaunancestro.Eltercercaso
manejalaposibilidadrestanteEjercicio22,35lepidequedemostrarquetaluna
.uborde/Esunbordedelanterosiu:d<:dyunbordetransversalusi:d>:d.
Ungrafonodirigidopuedeimplicarciertaambigedadenlaformaenqueclasificamosbordes,
desde.u/Y.u/sonrealmenteelmismoborde.Entalcaso,laclasificamos
bordequeelprimertipoenlalistadeclasificacinqueseaplica.Demaneraequivalente(verEx
Ercis22,36),laclasificamoselbordedeacuerdoconcualquierade.u/O.u/la
debsquedaencuentraenprimerlugar.
Vamosademostrarquebordesanterioresycruzadasnosedannuncaenunabsquedaenprofundidadde
ungrafonodirigido.

teorema22.10
EnunabsquedaenprofundidaddeungrafonodirigidoG,todaslasaristasdeGestantounrbol
bordeofiloatrs.

PruebaDeje.u/SerunaventajaarbitrariadeG,ysupongamos,sinprdidadegeneralidad
queu:d<:d.Acontinuacin,labsquedadebedescubriryacabadoantesdequetermineu
(Mientrasqueuesgris),yaestenlalistadeadyacenciadeu.Silaprimeravezquelabsqueda
https://translate.googleusercontent.com/translate_f 19/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
explora.uborde/,Esenladireccindeupara,acontinuacin, essindescubrir
(Blanco)hastaesemomento,puesdelocontrariolabsquedahabraexploradoesteborde
yaenladireccinde parati.Porlotanto,.u/Seconvierteenunbordederbol.Siel
bsquedaexplora.u/Primeroenladireccindeau,entonces.u/Esunbordeposterior,
yaqueuestodavagrisenelmomentoseexploraprimeroelborde.

Veremosvariasaplicacionesdeestosteoremasenlassiguientessecciones.

Ceremonias

22,31
Hagaungrfico3por3confilasycolumnasBLANCO,GRISyNEGRO.En
.icadaclulaj/,indicarsi,encualquiermomentoduranteunabsquedaenprofundidaddeundi
grficorected,nopuedehaberunbordedeunvrticedelcoloriaunvrticedelcolorj.
Paracadabordeposible,indiquequtipodebordequepuedeser.Hacerunasegundatales
tabladebsquedaenprofundidaddeungrafonodirigido.

22,32
Mostrarcmolabsquedaenprofundidadfuncionaenelgrficodelafigura22.6.Supongaquela
paraelbucledelaslneas57delprocedimientoDFSconsideralosvrticesenordenalfabtico
orden,ysesuponequecadalistadeadyacenciaseordenaalfabticamente.Mostrarla
descubrimientoytiemposdeacabadoparacadavrtice,ymostrarlaclasificacindecada
borde.

Pgina32

22.3Profundidadprimerabsqueda 611

Q R

S T Usted

V W x Y

Figura22.6Ungrafodirigidoparasuusoenlosejercicios22.32y22.52.

22,33
Mostrarlaestructuraparntesisdelabsquedaenprofundidaddelafigura22.4.

22,34
Muestranqueelusodeunsolobitparaalmacenarcadacolordevrticebastaconelargumentodeque
elprocedimientoDFSproduciraelmismoresultadosilalnea3delDFSVISITera
remoto.

22,35
Demostrarque.uborde/es
a.unbordederbolodeprimeralneasiyslosiu:d<:d<:f<u:f,
segundo.unbordeposteriorsiyslosi:dUnU:d<u:fA:f,y
do.unbordetransversalsiyslosi:d<:f<u:d<u:f.

22,36
Demostrarqueenungrafonodirigido,lacalificacindeunborde.u/Comounbordederbolounaespalda
bordedeacuerdoasi.u/O.u/seencontraronporprimeravezduranteelprimeroenprofundidad
bsquedaesequivalentealaclasificacindeacuerdoconelordendeloscuatrotiposde
elesquemadeclasificacin.

22,37
ReescribirelprocedimientoDFS,utilizandounapilaparaeliminarlarecursividad.

22,38
DaruncontraejemploalaconjeturadequesiungrafodirigidoGcontieneunaruta
deua,ysiu:d<:denunabsquedaenprofundidaddeG,entoncesesundescendiente
deuenelbosqueprimeroenprofundidadproducida.

Pgina33

612 Captulo22deprimariaGrficoAlgoritmos
https://translate.googleusercontent.com/translate_f 20/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

22,39
DaruncontraejemploalaconjeturadequesiungrafodirigidoGcontieneunaruta
deua,cualquierbsquedaenprofundidaddebedarlugara:dUnU:f.

22,310
Modificarelpseudocdigoparalabsquedaenprofundidadparaqueseimprimaacabotodaslasaristasenel
dirigidagrficoG,juntoconsutipo.Mostrarqumodificaciones,silashubiere,quenecesita
paraquesiGesnodirigido.

22,311
Aexplicarcmounauvrticedeungrafodirigidopuedeterminarenunrboldecontencinprimeroenprofundidad
ingnicamenteu,apesardequeutieneambosbordesentrantesysalientesenG.

22,312
DemuestranquesepuedeutilizarunabsquedaenprofundidaddeungrafonodirigidoGparaidentificarel
componentesconexasdeG,yqueelbosqueprimeroenprofundidadcontieneelmayornmeroderboles
Gcomosehaconectadocomponentes.Msprecisamente,mostrarcmomodificarprimeroenprofundidad
bsquedaparaqueleasignaacadavrticeunaetiquetaentera:ccentre1yk,
dondekeselnmerodecomponentesconectadosdeG,demaneraqueu:ccD:ccsi
yslosiTyestnenelmismocomponenteconectado.

22,313?
UngrafodirigidoGD.VE/estconectadaporseparadosiuimplicaqueGcontiene
alosumouncaminosimpledeuaparatodoslosvrticesu2V.Ofrecerunarespuestaeficiente
algoritmoparadeterminarsiesonoungrafodirigidoestconectadaporseparado.

22.4clasificacintopolgica

Enestaseccinsemuestracmopodemosusarlabsquedaenprofundidadparallevaracabounaordenacintopolgica
deungrafodirigidoacclico,oun"dag",comosellamaaveces.Unaclasificacintopolgica
deundagGD.VE/esunaordenacinlinealdetodossusvrticestalquesiGcontieneuna
.uborde/,Entoncesuapareceantesenelordenamiento.(Silagrficacontieneunciclo,
entonceshayunaordenacinlinealesposible.)Podemosverunaclasificacintopolgicadeungrficocomo
unaordenacindesusvrticesalolargodeunalneahorizontal,demodoquetodoslosbordesdirigidosvandesde
deizquierdaaderecha.clasificacintopolgicaesporlotantodiferentedelaclasehabitualde"clasificacin"
estudiadosenlaParteII.
Muchasaplicacionesutilizandirigidosacclicosgrficosparaindicarprecedenciasentre
eventos.Lafigura22.7daunejemploquesepresentacuandoelprofesorseponeBumstead
vestirseporlamaana.Elprofesordebeponerseciertasprendasdevestirantesdequeotros
(porejemplo,calcetinesantesdezapatos).Otrosartculospuedenserpuestosenencualquierorden(porejemplo,mediasy

Pgina34

22.4clasificacintopolgica 613

11/16calzoncillos calcetines
17/18
reloj 9/10
12/15pantalones zapatos13/14
camisa
1/8
(un) 6/7 cinturn
Corbata
2/5

chaqueta
3/4

calcetinescalzoncillos
(segundo) pantalones
zapatos reloj camisa cinturnCorbatachaqueta
17/18 11/16 12/15 13/14 9/10 1/8 6/7 2/5 3/4

Lafigura22.7(a)profesorordenaBumsteadtopolgicamentesuropaalvestirse.Cada
.uaristadirigida/Significaquelaprendaudebecolocarseantesdelaconfeccin.Eldescubrimientoy
tiemposdeacabadodeunabsquedaenprofundidadsemuestranjuntoacadavrtice.(b)Elmismogrficomuestra
topolgicamenteordenados,consusvrticesdispuestosdeizquierdaaderechaconelfindedisminuireltiempodeacabado.
Todoslosbordesdirigidosvandeizquierdaaderecha.

pantalones).Unaaristadirigida.u/EnelGDAdelafigura22.7(a)indicaquelaprendadevestiru
debensepusoantesdeprendadevestir.Unaclasificacintopolgicadeestedagporlotanto,dauna
pedirparavestirse.Lafigura22.7(b)muestraelGDAtopolgicamenteordenadoscomouna
ordenamientodelosvrticesalolargodeunalneahorizontaldetalmaneraquetodoslosbordesdirigidosvandeizquierda
Aladerecha.
ElsiguientealgoritmosencilloordenatopolgicamenteunGDA:

https://translate.googleusercontent.com/translate_f 21/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
TOPOLOGICALSORT.G/
1llamadaDFS.G/paracalcularlostiemposdeacabado:fparacadavrtice
2,yaquecadavrticeestterminado,insertarloenlapartefrontaldeunalistaenlazada
3devolverlalistaenlazadadevrtices

Lafigura22.7(b)muestracmoaparecenlosvrticestopolgicamenteordenadosenordeninverso
desustiemposdeacabado.
Podemosrealizarunaordenacintopolgicaeneltiempo,.VCE/,yaquelabsquedaenprofundidad
toma,.VCE/horaysetardaO.1/horaparainsertarcadaunodelosvrticesjJVen
lapartedelanteradelalistaenlazada.
Sepruebalaexactituddeestealgoritmousandoelsiguientelemaclavecarac
acterizinggrficosacclicosdirigidos.

Pgina35

614 Captulo22deprimariaGrficoAlgoritmos

lema22.11
UngrafodirigidoGesacclicosiyslosiunabsquedaenprofundidaddeGnodalaespalda
bordes.

Prueba):Supongamosqueunabsquedaenprofundidadproduceuna.ubordeposterior/.Entonces
vrticeesunantepasadodeuvrticeenelbosqueprimeroenprofundidad.Porlotanto,Gcontieneunaruta
apartirdeu,yelbordeposterior.u/Completaunciclo.
(:SupongamosqueGcontieneunciclocSedemuestraqueunabsquedaenprofundidaddeG.
seobtieneunbordeposterior.DejarserelprimervrticequesedescubrienC,ydejar.u/estar
elbordeanterior,enelc.Eneltiempo:D,losvrticesdeCformanunatrayectoriadevrticesblanco
deparau.Porelteoremadeblancoruta,uvrticeseconvierteenundescendientedela
primeroenprofundidaddelosbosques.Porlotanto,.u/Esunbordeposterior.

teorema22.12
TOPOLOGICALSORTproduceunaordenacintopolgicadelgrafodirigidoacclico
proporcionadacomosuentrada.

PruebaSupongamosqueDFSseejecutaenundeterminadodagGD.VE/Finlandiaparadeterminar
Ishingvecesporsusvrtices.Bastacondemostrarqueparacualquierpardeversindistinta
TICESu2V,siGcontieneunbordedeua,entonces:f<u:f.considerarcualquier
.uborde/ExploradoporDFS.G/.Cuandoseexploraesteborde,nopuedeserdecolorgris,
desdeentoncesseraunantepasadodeuy.u/Seraunbordeposterior,contradiccin
dictingLema22.11.Porlotanto,debeserdecolorblancoonegro.Siesdecolorblanco,
seconvierteenundescendientedeu,yas:f<u:f.Siesdecolornegro,queyahasido
terminado,demodoque:fyasehaestablecido.Dadoquetodavaestamosexplorandodeu,
sinembargo,tienequeasignarunamarcadetiempodeu:f,yas,unavezquehacemos,tendremos:f<u:f
ascomo.Porlotanto,paracualquier.Uborde/EnelGDA,tenemos:f<u:f,loquedemuestrala
teorema.

Ceremonias

22,41
MostrarelordendelosvrticesproducidosporTOPOLOGICALSORTcuandoseejecutaen
elGDAdelafigura22.8,bajoelsupuestodeejercicio22,32.

22,42
DarunalgoritmodetiempolinealquetomacomoentradaungrafoacclicodirigidoGD
.VE/ydosvrticessyt,ydevuelveelnmeroderutassimplesdes
atenG.Porejemplo,elgrficoacclicodirigidodelaFigura22.8contieneexactamente
cuatrocaminossencillosdesdeelvrticeavrticep:po,PORY,posry,ypsry.
(Sualgoritmonecesitasloparacontarloscaminossencillos,noenumeraellos.)

Pgina36

22.5componentesfuertementeconectados 615

metro norte O pag

Q R S

T Usted V W

x Y Z

https://translate.googleusercontent.com/translate_f 22/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Figura22.8UnGDAparaclasificacintopolgica.

22,43
DarunalgoritmoquedeterminasiungrafonodirigidodadaGD
.VE/contieneunciclo.SualgoritmodebeejecutarenOV/hora,independiente
dejej.

22,44
Probarorefutar:SiungrafodirigidoGcontieneciclos,entoncesTOPOLOGICAL
STRO.G/produceunordenamientovrticequereducealmnimoelnmerodelos"malos"bordes
quesonincompatiblesconelordenamientoproducido.

22,45
OtraformaderealizarlaclasificacintopolgicaenungrficoacclicodirigidoGD
.VE/esencontrarenvariasocasionesenunvrticedegrado0,lasalidadeella,yretirarlojuntocon
todossusbordessalientesdelagrfica.Explicacmoimplementarestaideatan
queseejecutaentiempoOVCE/.QuocurreconestealgoritmosiGtieneciclos?

22.5componentesfuertementeconectados

Ahoraconsideramosunaaplicacinclsicadelabsquedaenprofundidad:descomponerundi
rectedgrficoensuscomponentesfuertementeconectados.Enestaseccinsemuestracmohacerlo
asqueusardosbsquedasprimeroenprofundidad.Muchosalgoritmosquetrabajancongrficosdirigidos
comenzarconunadescomposicintal.Despusdedescomponerelgrficoenfuertementecon
componentesconectados,talesalgoritmosseejecutanporseparadoencadaunoyluegocombinar
lassolucionesdeacuerdoconlaestructuradelasconexionesentreloscomponentes.
RecuerdequeenelApndiceBqueuncomponentefuertementeconexadeundirige
grficaGD.VE/esunconjuntomximodevrticesCVtalqueparacadapar
devrticesuyenC,quetienentantouyuesdecir,losvrticesuy
sonaccesiblesdesdeunoalotro.Lafigura22.9muestraunejemplo.

Pgina37

616 Captulo22deprimariaGrficoAlgoritmos

un segundo do re
13/14 11/16 1/10 8/9
(un)
12/15 3/4 2/7 5/6
mi F gramo marido

un segundo do re

(segundo)

mi F gramo marido

discoscompactos
(do) abe
Fg marido

Figura22.9(a)ungrficodirigidoG.CadareginsombreadaesuncomponentefuertementeconectadodeG.
Cadavrticeseetiquetaconsudescubrimientoylostiemposdeacabadoenunabsquedaenprofundidad,ylosbordesdelosrboles
estnsombreados.(b)LagrficaGT,latranspuestadeG,conelbosqueprimeroenprofundidadcalculadaenlalnea3
deStronglyCONNECTEDCOMPONENTESmuestranybordesderbolessombreados.Cadafuertementeconectados
componentecorrespondeaunrbolprimeroenprofundidad.Losvrticesb,c,g,yh,queestnfuertementesombreada,son
lasracesdelosrbolesprimeroenprofundidadproducidosporlabsquedaenprofundidaddeGT.(c)Elcomponenteacclico
grafoGSCCobtienemediantelacontratacindetodoslosbordesdentrodecadacomponentefuertementeconectadodemodoG
queslounnicovrticepermaneceencadacomponente.

NuestroalgoritmoparaencontrarcomponentesfuertementeconexasdeungrafoGD
.VE/usalatranspuestadeG,quesedefinienelejercicio22,13serel
grafoGTD.VET/,dondeETDfu/W.u/2Ej.Esdecir,ETconsisteen
losbordesdeGconsusdireccionesinvertidas.Dadaunaadyacencialistaderepresentacin
cindeG,eltiempoparacrearGTesOVCE/.EsinteresanteobservarqueG
yGTtieneexactamentelosmismoscomponentesfuertementeconectados:uysonREACH
capazdeotraenGsiyslosisonaccesibledesdeunoalotroenGT.
Figura22.9(b)muestralatranspuestadelagrficadelafigura22.9(a),conelfuertemente
componentesconectadosalasombra.

https://translate.googleusercontent.com/translate_f 23/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina38

22.5componentesfuertementeconectados 617

Elsiguienteentiempolineal(esdecir,,.VCE/tiempo)algoritmocalculalafuerza
componentesconexasdeungrafodirigidoGD.VE/sutilizandodosprimeroenprofundidad
bsquedas,unodeGyGenunacamiseta.
Strongly CONNECTEDCOMPONENTES.G/
1llamadaDFS.G/paracalcularlostiemposdeacabadou:fparacadavrticeu
2calcularGT
3llamarDFS.GT/,peroenelbucleprincipaldeDFS,considerelosvrtices
enordendecrecientedeu:f(comocomputadoenlnea1)
4Salidadelosvrticesdecadarbolenelbosqueprimeroenprofundidadformadasenlalnea3comouna
separadacomponentefuertementeconectado
Laideadetrsdeestealgoritmoprovienedeunapropiedadclavedelcomponente
GrficoGSCCD.VSCCESCC/,quesedefinedelasiguientemanera.SupongamosqueG
sehaconectadofirmementecomponentesC1C2:::Ck.ElconjuntodevrticesVSCCes
f12:::kg,ycontieneunvrticeiparacadacompofuertementeconectado
nenteCideG.Hayunarco.ij/2ESCCsiGcontieneunaaristadirigida.xy/
paraalgunosx2Ciyalgunosy2Cj.Vistodeotromodo,mediantelacontratacindetodo
bordescuyosvrticessonincidentesdentrodelmismocomponentefuertementeconectado
deG,lagrficaresultanteesGSCC.Figura22.9(c)muestraelgrficodecomponentede
elgrficodelaFigura22.9(a).
Lapropiedadclaveesqueelgrficodecomponenteesundag,quelasiguiente
lemaimplica.

lema22.13
DejarqueCyC0seandistintoscomponentesfuertementeconectadosengrafodirigidoGD
.VE/,seaU2C,seau002C0,ysupongamosqueGcontieneunarutauu0.
EntoncesGnopuedetambincontenerunaruta0.

PruebaSiGcontieneunaruta0,EntoncescontienecaminosUu00y
0UDeestemodo,uy0sonaccesiblesentres,tantocontradiciendo
elsupuestodequeCyC0sondistintoscomponentesfuertementeconectados.

Veremosque,considerandolosvrticesenlasegundabsquedaenprofundidadenladespolarizacin
ordendelostiemposdeacabadoquesecalcularonenelprimerprimeroenprofundidadarrugar
bsqueda,queson,enesencia,visitandolosvrticesdelgrafocomponente(cadaunadelas
quecorrespondeauncomponentefuertementeconectadodeG)entopolgicamenteordenadas
orden.
DebidoaqueelStrongly CONNECTEDCOMPONENTESprocedimientorealizados
profundidadprimerasbsquedas,existeelpotencialparalaambigedadcuandodiscutimosu:D
ou:f.Enestaseccin,estosvaloresserefierensiemprealdescubrimientoyacabado
vecescalculadasporlaprimerallamadadelaDFS,enlalnea1.

Pgina39

618 Captulo22deprimariaGrficoAlgoritmos

Extendemoslanotacinparaeldescubrimientoydefinalizacin,aconjuntosdevrtices.
SiTV,acontinuacin,definimosdU/DminU2Ufu:dgyf.U/DmaxU2Ufu:fg.
Esdecir,dU/yf.U/sonelmomentomstempranodescubrimientoylaltimahoradefinalizacin,
respectivamente,decualquiervrticeenU.
Elsiguientelemaysucorolariodanunapropiedadclaverelacionadafuertementecon
componentesconectadosylostiemposdellegadaenlaprimerabsquedaenprofundidad.

lema22.14
DejarqueCyC0seandistintoscomponentesfuertementeconectadosengrafodirigidoGD
.VE/.Supongamosquehayuna.Uborde/2E,dondeu2Cy2C0.Entonces
f.C/>f.C0/.

PruebaSeconsiderandoscasos,dependiendodelacompofuertementeconectada
nente,CoC0,tuvieronelprimervrticedescubiertodurantelabsquedaenprofundidad.
SidC/<dC0/,seaXelprimervrticedescubiertoenC.Enelmomentox:d,todaversin
ticasenCyC0sondecolorblanco.Enesemomento,Gcontieneunarutadexacadavrtice
enCqueconsistesolamentedevrticesblancos.Debidoa.u/2E,paracualquiervrticew2C0,
tambinhayuncaminoenGenelmomentox:ddexawqueconsistesolamentedevrticesblanco:
xu!w.Porelteoremadeblancoruta,todoslosvrticesenCyC0seconvierten
descendientesdexenelrboldeprofundidadprimero.PorCorolario22.8,xtienelaltimadeacabado
eltiempodecualquieradesusdescendientes,yasx:fDF.C/>f.C0/.

https://translate.googleusercontent.com/translate_f 24/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
SiporelcontrariotenemosdC/>dC0/,seaYelprimervrticedescubiertoenC0.
Alahoray:d,todoslosvrticesenC0sondecolorblancoyGcontieneunarutadeYacadauno
vrticeenC0queconsistesolamenteenlosvrticesdecolorblanco.Porelteoremadeblancoruta,todaversin
ticasenC0seconviertenendescendientesdeyenelrboldeprimeroenprofundidad,yporelCorolario22.8,
y:fD.Cf0/.Alahoray:d,todoslosvrticesenCsondecolorblanco.Dadoquehayunborde.u/
deCaC0,Lema22.13implicaquenopuedehaberuncaminodeC0aC.
Porlotanto,ningnvrticeenCesaccesibledesdey.Enelmomentoy:f,porlotanto,todoslosvrticesenC
sontodavablanco.Porlotanto,paracualquiervrticew2C,tenemosw:f>y:f,loqueimplica
quef.C/>f.C0/.

ElsiguientecorolarionosdicequecadaaristaenGTquevaentrediferentes
componentesfuertementeconectadospasadeuncomponenteconunacabadoantes
tiempo(enlaprimerabsquedaenprofundidad)auncomponenteconuntiempodeacabadomstarde.

corolario22.15
DejarqueCyC0seandistintoscomponentesfuertementeconectadosengrafodirigidoGD
.VE/.Supongamosquehayuna.Uborde/2ET,dondeT2yC2C0.Entonces
f.C/<f.C0/.

Pgina40

22.5componentesfuertementeconectados 619

PruebaDesde.u/2ET,tenemos.u/2E.Debidoaqueelconfuertemente
componentesconectadosdeGyGTsonlosmismos,Lemma22,14implicaque
f.C/<f.C0/.

Corolario22.15proporcionalaclaveparaentenderporquelfuertementeconectada
componentesalgoritmofunciona.Examinemosloqueocurrecuandoserealiceel
segundabsquedaenprofundidad,queestenGT.Comenzamosconlafuerzaconectada
componenteC.Ccuyoacabadoeltiempof/esmxima.Labsquedaseiniciadesde
algunosvrticesx2C,yvisitatodoslosvrticesenC.PorCorolario22.15,GTcontiene
nohaybordesdeCacualquierotrocomponentefuertementeconectado,yaslabsqueda
dexnovaavisitarvrticesencualquierotrocomponente.Porlotanto,elrbolenraizadoenx
contieneexactamentelosvrticesdeC.DespusdehabercompletadovisitartodoslosvrticesenC,
labsquedaenlneade3seleccionacomorazunvrticedealgnotrofuertementeconectada
componenteC0cuyoacabadotiempo.Cf0/esmximasobretodosloscomponentesdeotros
deC.Unavezms,labsquedavisitartodoslosvrticesenC0,sinoporelCorolario22.15,
lasnicasaristasenGTdeC0acualquierotrocomponentedebeaC,loquenos
yahanvisitado.Engeneral,cuandolabsquedaenprofundidaddeGTenlalnea3visitas
cualquiercomponentefuertementeconectada,losbordesdecadacomponentequedebeser
componentesquelabsquedayavisitado.Cadarbolprimeroenprofundidad,porlotanto,ser
exactamenteunoconectadofuertementecomponente.Elsiguienteteoremaformalizaeste
argumento.

teorema22.16
ElStrongly CONNECTEDCOMPONENTESprocedimientocalculacorrectamenteel
conectadafirmementecomponentesdelgrafodirigidoGproporcioncomosuentrada.

PruebaArgumentamosporinduccinsobreelnmeroderbolesprimeroenprofundidadqueseencuentraenel
bsquedaenprofundidaddeGTenlalnea3quelosvrticesdecadarbolformanunfuerte
componenteconectado.Lahiptesisdeinduccinesquelosprimerosrboleskproducen
enlalnea3soncomponentesfuertementeconectados.Labaseparalainduccin,cuando
kD0,estrivial.
Enelpasoinductivo,asumimosquecadaunodelosprimeroskrbolesprimeroenprofundidadproducidos
enlalnea3esuncomponentefuertementeconectado,yconsideramosla.kC1/rbolst
producida.Dejequelarazdeesterbolseavrticeu,yseaUenlafuertementeconectados
componenteC.Debidoalaformaenqueelegimosracesenlabsquedaenprofundidadenlalnea3,
u:fDIG/>fC0/paracualquiercomponentefuertementeconectadoC0quenoseaC
queaunnohasidovisitado.Porlahiptesisdeinduccin,enelmomentoenquelabsqueda
visitasu,todoslosdemsvrticesdeCsondecolorblanco.Porelteoremadeblancopath,porlotanto,todo
otrosvrticesdeCsondescendientesdeUensurboldeprimeroenprofundidad.Porotraparte,porel
hiptesisdeinduccinyCorolario22.15,losbordesenGTquedejanCdebenestar
alconectadafirmementecomponentesqueyahansidovisitados.Porlotanto,novrtice

Pgina41

620 Captulo22deprimariaGrficoAlgoritmos

encualquiercomponentefuertementeconexadistintadeChabrundescendientedeUdurante

https://translate.googleusercontent.com/translate_f 25/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
labsquedaenprofundidaddeGT.Porlotanto,losvrticesdelrboldeprofundidadprimeroenGTquees
enraizadaenFormadeUexactamenteuncomponentefuertementeconectado,quecompletala
pasoinductivoypruebadeello.

Aquesotramaneradeverlaformaenqueoperalasegundabsquedaenprofundidad.Estafa
Siderlagrficacomponente.GT/SCCdeGT.Sihacemosunmapadecadafuertementeconectada
componentevisitadoenlasegundabsquedaenprofundidadaunvrticede.GT/SCC,elsector
ondprimeroenprofundidadvisitasdebsquedavrticesde.GT/SCCenelreversodeuntopolgicamente
elordenestablecido.Siinvertimoslosbordesde.GT/SCC,obtenemoselgrfico..gT/SCC/T.
Debido..gT/SCC/TDGSCC(vaseelejercicio22,54),lasegundabsquedaenprofundidad
visitalasvrticesdeGSCCconelfintopolgicamenteordenados.

Ceremonias

22,51
Cmopuedeelnmerodecomponentesfuertementeconexosdeuncambiogrficoquesiunnuevo
Seaadeelborde?

22,52
MostrarcmoelprocedimientoStrongly CONNECTEDCOMPONENTEStrabajaenel
grficodelaFigura22.6.Enconcreto,mostrarlostiemposdellegadacomputadoenlalnea1y
elbosqueseproduceenlalnea3.Supongamosqueelbucledelaslneas57delaDFSconsidera
vrticesenordenalfabticoyquelaslistasdeadyacenciaestnenordenalfabtico.

22,53
ProfesordeBaconafirmaqueelalgoritmodecomponentesfuertementeconexas
seramssimplesiseutilizala(enlugardelatranspuesta)grficooriginalenel
segundabsquedaenprofundidadyexaminlosvrticesconelfindeaumentarelacabado
veces.Estealgoritmomssimplesiempreproduceresultadoscorrectos?

22,54
DemostrarqueparacualquiergrafodirigidoG,tenemos..gT/SCC/TDGSCC.Esoesel
transposicindelagrficacomponentedeGTeselmismoqueelgrficodecomponentedeG.

22,55
DunOVCE/algoritmotiempoparacalcularlagrficadeuncomponentedirigido
grficaGD.VE/.Asegresedequenoesalosumounaaristaentredosvrtices
enelgrficoreferenteasualgoritmoproduce.

Pgina42

Losproblemasrelacionadosconelcaptulo22 621

22,56
DadoungrafodirigidoGD.VE/,explicarcmocrearotrogrficoG0D
.VE0/talque(a)G0tienelosmismoscomponentesfuertementeconectadoscomoG,(b)G0
tieneelmismogrficocomocomponenteG,y(c)E0eslomspequeoposible.describiruna
rpidoalgoritmoparacalcularG0.

22,57
UngrafodirigidoGD.VE/sesemiconnectedsi,paratodoslosparesdevrticesu2V,
tenemosu o UDarunalgoritmoeficienteparadeterminarsi
onoseGsemiconnected.Demostrarqueelalgoritmoescorrecto,yanalizarsu
tiempodeejecucin.

Problemas

221Clasificacindelosbordesdelabsquedaenamplitud
Unbosqueprimeroenprofundidadclasificalosbordesdeungrficoenrbol,atrs,adelante,y
bordestransversales.Unrbolprimeroenamplitudtambinsepuedeutilizarparaclasificarlosbordesalcanzables
delafuentedelabsquedaenlasmismascuatrocategoras.

a.Demostrarqueenunabsquedaenamplituddeungrafonodirigido,elsiguientePROP
propiesostienen:
1.Nohaybordesposterioresynohaybordesdelanteros.
2.Paracada.ubordedelrbol/,Tenemos:dDu:dC1.
3.Paracada.ubordetransversal/,Tenemos:dDu:do:dDu:dC1.

segundo.Demostrarqueenunabsquedaenamplituddeungrafodirigido,lassiguientespropiedades
sostener:
1.Nohaybordesdelanteros.
2.Paracada.ubordedelrbol/,Tenemos:dDu:dC1.
https://translate.googleusercontent.com/translate_f 26/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
3.Paracada.ubordetransversal/,Tenemos:dUnU:dC1.
4.Paracada.ubordeposterior/,Tenemos0a:dUnU:d.

222puntosdearticulacin,puentesyvrticedecorte
DejeGD.VE/unagrficaconexanodirigida.UnpuntodearticulacindeGes
unvrticecuyaeliminacindesconectaG.UnpuentedeGesunaventajacuyaeliminacin
desconexionesG.UnbiconexascomponentedeGesunconjuntomximodearistastales
quecualquieradelosdosbordesenelconjuntodementiraenunciclosimplecomn.Lafigura22.10ilustra

Pgina43

622 Captulo22deprimariaGrficoAlgoritmos

2
1 6
4
3

Figura22.10Laarticulacinpuntos,puentesyvrticedecortedeuncomunicado,indiviso
rectedgrficoparasuusoenelproblema222.Lospuntosdearticulacinsonlosvrticesengranmedidaalasombra,las
puentessonlosbordesfuertementesombreadas,ylasvrticedecortesonlosbordesdelasombra
regiones,conunBCCnumeracinmuestran.

estasdefiniciones.Podemosdeterminarpuntosdearticulacin,puentes,ybiconexas
componentesqueutilizanlabsquedaenprofundidad.DejeGD.VE/seaunrbolprimeroenprofundidaddeG.
a.DemostrarquelarazdeGesunpuntodearticulacinGsiyslositieneal
menosdosniosenG.

segundo.DejarserunvrticequenoesrazdeG.DemostrarqueesunpuntodearticulacindeGsiy
slositieneunhijosdetalmaneraquenohaybordeposteriordesocualquierdescendiente
delaSaunancestroadecuadode.

do.Dejar
(
:D
:BajaminD
w:dW.uw/esunbordeposteriorporalgunaudescendientede:

Mostrarcmocalcular:bajaparatodoslosvrticesVen2OE/hora.

re.MostrarcmocalculartodoslospuntosdearticulacindeOE/hora.

mi.DemostrarqueunbordedeGesunpuentesiyslosinoseencuentraenningnsencilla
ciclodeG.

F.MostrarcmocalculartodoslospuentesdeGenOE/hora.

gramo.DemostrarquelasvrticedecortedeparticinGnonbridgelosbordesdeG.

marido.DunalgoritmodeOE/tiempoparaetiquetarcadaaristaedeGconuninpositivo
Tegere:BCCtalquee:BCCDE0:BCCsiyslosielectrnicoy0estnenlamisma
vrticedecorte.

Pgina44

Notasparaelcaptulo22 623

223giradeEuler
UnrecorridodeEulerdeunfuertementeconectada,grficodirigidoGD.VE/esuncicloque
atraviesacadabordedeGexactamenteunavez,aunquepuedevisitarunvrticemsde
unavez.

a.DemostrarqueGtieneunrecorridodeEulersiyslosi,engrados./Dcabogrados./para
cadavrticeV2.

segundo.Describirunalgoritmo/OEtiempoparaencontrarunrecorridodeEulerdeGsiexiste.(Pista:
Combinarlosciclosdebordediscontinuo.)

224Alcanzabilidad
DejeGD.VE/ungrafodirigidoenelquecadavrticeu2Vestmarcadacon
https://translate.googleusercontent.com/translate_f 27/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
unnmeroenteronicoLu/Delconjuntof12:::JVjg.Paracadavrticeu2V,ymucho
Ru/Df2VWuGelconjuntodevrticesquesonaccesiblesdesdeu.Definir
min.u/queeselvrticedeRu/cuyaetiquetaesmnimo,esdecir,min.u/eselvrtice
detalmaneraqueL./DminfL.w/Ww2Ru/g.DunOVCE/algoritmoquetiempo
calculamin.u/paratodoslosvrticesu2v.

Lasnotasdecaptulos

Incluso[103]yTarjan[330]sonexcelentesreferenciasparaalgoritmosdegrafos.
AmplitudprimerabsquedafuedescubiertoporMoore[260]enelcontextodelabsquedade
caminosatravsdeloslaberintos.Lee[226]descubriindependientementeelmismoalgoritmoen
elcontextodeenrutamientodecablesenlasplacasdecircuitos.
HopcroftyTarjan[178]defendidoelusodelarepresentacindeadyacencialista
sobrelarepresentacinpormatrizdeadyacenciadegrafosdispersosyfueronlosprimerosen
reconocerlaimportanciadealgoritmosdebsquedaenprofundidad.Labsquedaenprofundidadtiene
sidoampliamenteutilizadodesdeladcadade1950,especialmenteenlosprogramasdeinteligenciaartificial.
Tarjan[327]diounalgoritmodetiempolinealparaencontrarnentefuertementeconectada
Nentes.ElalgoritmodecomponentesconectadosfirmementeenlaSeccin22.5seadapta
deAho,Hopcroft,yUllman[6],queacreditarloalSRKosaraju(sinpublicar)
yM.Sharir[314].Gabow[119]tambindesarrollunalgoritmoparaconfuertemente
componentesconectadosquesebasaenlosciclosdecontratacinyutilizadospilasparahacer
queseejecuteeneltiempolineal.Knuth[209]fueelprimeroenhacerunalgoritmodetiempolinealpara
clasificacintopolgica.

Pgina45

23 Losrbolesdeexpansinmnimos

diseosdecircuitoselectrnicosamenudotienenquehacerlospasadoresdevarioscomponenteselec
elctricamenteequivalentealcablearjuntos.Parainterconectarunconjuntodenpasadores,podemos
utilizarunadisposicinden1cables,cadaunoqueconectandospasadores.Detodosesosdisposicin
tos,elqueutilizalamenorcantidaddecableesgeneralmenteelmsdeseable.
Podemosmodelaresteproblemadecableadoconungrafoconexo,nodirigidoGD
.VE/,dondeVeselconjuntodepines,Eeselconjuntodeposiblesinterconexionesentre
paresdepasadores,yparacada.Uborde/2E,tenemosunpesowu/especificando
elcoste(cantidaddecablenecesario)paraconectaruy.acontinuacin,deseamosencontraruna
subgrupoacclicoTAEqueconectatodoslosvrticesycuyopesototal
x
WT/D Wu/
.u/2T
sereducealmnimo.ComoTesacclicayconectatodoslosvrtices,debeformarunrbol,
quellamamosunrboldeexpansin,yaque"abarca"elgrficoG.quellamamoselproblemadela
ladeterminacindelrbolTelproblematreeexpansinmnimo.1Lafigura23.1muestra
unejemplodeungrficoconectadoyunrboldeexpansinmnimo.
Enestecaptulo,examinaremosdosalgoritmospararesolverelmnimo
problemaspanningtree:elalgoritmodeKruskalyelalgoritmodePrim.Podemosfcilmente
hacenquecadaunodeellosseejecutaneneltiempoOELGV/binariosusandomontonesordinarios.Medianteeluso
montonesdeFibonacci,elalgoritmodePrimseejecutaentiempoOECVLGV/,loquemejora
delaejecucinbinarymontnsijVjesmuchomenorquejej.
Losdosalgoritmossonalgoritmoscodiciosos,comosedescribeenelcaptulo16.Cada
elpasodeunalgoritmovorazdebehacerunadevariasopcionesposibles.elcodicioso
defensoresdelaestrategiadehacerlaeleccinqueeselmejorenestemomento.ungiatales
EGYgeneralmentenogarantizaquesiemprevaaencontrarsolucionesptimasanivelmundial

1Lafrase"rboldeexpansinmnima"esunaformaabreviadadelafrase"mnimopesoqueabarca
rbol."Noson,porejemplo,reduciendoalmnimoelnmerodearistasenT,yaquetodoslosrbolesdeexpansintienen
exactamentejVj1aristasporelteoremaB.2.

https://translate.googleusercontent.com/translate_f 28/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina46

23.1Elcrecimientodeunrboldeexpansinmnimo 625

8 7
segundo do re
4 9
2
un 11 yo 4 14 mi
7 6
8 10
marido gramo F
1 2

Figura23.1Unrboldeexpansinmnimoparaungrafoconexo.Lospesosenlosbordessemuestran,
ylosbordesdeunrboldeexpansinmnimoestnsombreados.Elpesototaldelrbolquesemuestraes37.Este
rboldeexpansinmnimonoesnica:laeliminacindela.bbordec/ysusustitucinporelborde.amarido/
produceotrorboldeexpansinconelpeso37.

alosproblemas.Paraelproblemaspanningtreemnimo,sinembargo,podemosprobarque
ciertasestrategiascodiciososhacenrendirunrboldeexpansinconelmnimopeso.Apesardeque
ustedpuedeleerestecaptulo,conindependenciadelcaptulo16,losmtodosvoracespre
aqupresentamossonunaclsicaaplicacindelosconceptostericosintroducidosall.
Seccin23.1introduceunmtododespanningtreemnimo"genrico"quecrece
unrboldeexpansinmediantelaadicindeunbordealavez.Seccin23.2dadosalgoritmos
queimplementanelmtodogenrico.Elprimeralgoritmo,debidoaKruskal,essimilar
alalgoritmodecomponentesconectadosdelaSeccin21.1.Lasegunda,debidoa
Prim,seasemejamscortoalgoritmodeDijkstracaminos(Seccin24.3).
Debidoaqueunrbolesuntipodegrfico,conelfindeserprecisosdebemosdefinirunrbolen
Lostrminosnoslodesusbordes,perosusvrticestambin.Aunqueestecaptulosecentra
enlosrbolesentrminosdesusbordes,queoperarenelentendidodequela
vrticesdeunrbolTsonlasqueunpocodebordedeTesincidentesobre.

23.1Elcrecimientodeunrboldeexpansinmnimo

Supongamosquetenemosunaconectada,grafonodirigidoGD.VE/conunpeso
funcinwWE!R,yquedeseanencontrarunrboldeexpansinmnimadeG.El
dosalgoritmosqueseconsideranenestecaptuloseutilizaunenfoquecodiciososalproblema,
aunquedifierenenlaformaenqueseaplicanesteenfoque.
Estaestrategiacodiciosoescapturadoporelsiguientemtodogenrico,quecrece
elrboldeexpansinmnimounbordealavez.Elmtodogenricogestionaunconjunto
Unadelasaristas,elmantenimientodelossiguientesinvariantesdebucle:
Antesdecadaiteracin,Aesunsubconjuntodeunrboldeexpansinmnimo.
Encadapaso,sedeterminaunborde.u/QuepodemosaadiraAsinviolar
estainvariante,enelsentidodequeA[fu/Gtambinesunsubconjuntodeunaexpansinmnimo

Pgina47

626 Captulo23mnimoSpanningTrees

rbol.LlamamosatalbordedeunbordeseguroparaA,yaquepodemosaadirasalvoauntiempo
elmantenimientodelainvariante.

GENERICMST.Gw/
1dC
2,mientrasqueAnoformaunrboldeexpansin
3 encontrarunborde.u/Queesseguroparacada
4 ADA[fu/gramo
5deretornoUn

Utilizamoselinvariantebuclecomosigue:
Inicializacin:Despusdelalnea1,elconjuntosatisfacetrivialmenteelinvarianteUnbucle.
Mantenimiento:Elbucledelaslneas24mantieneelinvariantemediantelaadicindesloessegura
bordes.
Terminacin:TodoslosbordesaadenaAestnenunrboldeexpansinmnimo,porloqueel
Unconjuntodevueltosenlalnea5debeserunrboldeexpansinmnimo.

Lapartedifciles,porsupuesto,encontrarunbordeseguroenlalnea3.Unodebeexistir,ya
cuandoseejecutalalnea3,elinvariantedictaquehayunrbolTqueabarcatales
queAunacamiseta.Enelmismotiempocuerpodelbucle,AdebeserunsubconjuntopropiodeT,y
porlotanto,tienequehaberun.Uborde/2Ttalque.u/62Ay.u/esseguro
para.
Enelrestodeestaseccin,proporcionamosunaregla(teorema23.1)paraRecognizer

https://translate.googleusercontent.com/translate_f 29/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
ingbordesseguras.Enlasiguienteseccinsedescribendosalgoritmosqueutilizanestareglaparaencontrar
bordesdeseguridadeficiente.
Enprimerlugarhayalgunasdefiniciones.Uncorte.SV
S/deungrafonodirigidoGD
.VE/esunaparticindeV.Lafigura23.2ilustraestaidea.Decimosqueunborde
.u/2Ecruzalos.ScorteV S/siunodesusextremosseencuentraenSyelotro
esenV S.SedicequeuncorterespetaunconjuntoAdelosbordessinohayventajaenunacruzala
cortar.Unbordeesunbordedeluzquecruzauncortesisupesoeselmnimodecualquieradelosbordes
cruzandoelcorte.Tengaencuentaquenopuedehabermsdeunodelosbordesdeluzquecruzauncorteen
elcasodelosvnculos.Demaneramsgeneral,sedicequeunbordeesunbordedeluzquesatisfaceuna
dadalapropiedadsisupesoeselmnimodecualquierbordequesatisfacelapropiedad.
Nuestraregladereconocimientodebordesdeseguridadestdadaporlasiguienteteorema.

teorema23.1
DejeGD.VE/ungrafoconectado,nodirigidoconunpesodevalorrealfuncin
wcindefinidaenE.SeaAunsubconjuntodeEqueseincluyeenalgunamnimo
rboldeexpansinparaG,ymucho.SV
S/sercualquiercortedeGquerespeteA,ydejarque.u/
serunbordedeluzdecruce.SVS/.Entonces,elborde.u/EsseguroparaA.

Pgina48

23.1Elcrecimientodeunrboldeexpansinmnimo 627

8 marido
un 7
4 11 yo 1
segundo 6
2 gramo
8 7 re 8
segundo do re
4 9 7
9 do 2
S 2 S
un 11 yo 4 14 mi 4
VS 7 6 VS mi 14
8 10
marido gramo F 10 F
1 2
S VS
(un) (segundo)

Figura23.2Dosformasdeveruncorte.SVS/delagrficadelaFigura23.1.(a)Negro
vrticesestnenelconjuntoS,yvrticesblancosestnenV
S.Losbordesquecruzanelcortesonaquellos
queconectalosvrticesdecolorblancoconnegrovrtices.Elborde.d,c/eselbordedeluznicaquecruzala
cortar.UnsubconjuntoAdelosbordesestalasombratengaencuentaquelos.ScorteV
S/Arespeta,yaqueningnbordedeuna
cruzaelcorte.(b)ElmismogrficoconlosvrticesenelconjuntoSdelaizquierdaylosvrticesenel
setV Saladerecha.Unbordecruzaelcortesiseconectaunvrticedelaizquierdaconunvrticeenel
derecho.

PruebaSeaTunrboldeexpansinmnimaqueincluyeA,ysupongamosqueT
nocontieneel.ubordedelaluz/,Yaquesilohace,hemosterminado.Deberiamos
construirotrorboldeexpansinmnimaT0queincluyeuna[fu/gmedianteelusodeuna
cortarypegartcnica,demostrandoasque.u/EsunaventajaseguraparaA.
Elborde.u/Formauncicloconlosbordesenelcaminosimplepdesdeu
enT,comolafigura23.3ilustra.DesdeUyestnenladosopuestosdela
cortar.SV S/,almenosunbordeenTseencuentraenelcaminosimplepytambincruza
elcorte.Vamos.xa/aalguienasborde.Elborde.xa/anoestenuna,porqueelcorte
respetaA.Desde.xa/aestenelcaminosimplenicadeuaenT,removible
ing.xy/rompeTendoscomponentes.Adicinde.u/Lesvuelveaconectarparaformar
unnuevorboldeexpansinT0fxa/g[fu/gramo.
DT
AcontinuacinmostramosqueT0esunrboldeexpansinmnimo.Desde.u/Esunaventajaligera
cruzando.SVS/y.xa/atambincruzaestecorte,Wu/wxa/a.Porlotanto,
WT0/DWT/wxY/Cwu/
UnWT/:

Pgina49

628 Captulo23mnimoSpanningTrees

https://translate.googleusercontent.com/translate_f 30/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Usted pag Y

Figura23.3Lademostracindelteorema23.1.VrticesnegrosestnenS,yvrticesblancosestnenV
S
LosbordesenelmnimoTrboldeexpansinsemuestran,perolosbordesenelgrficoGnoloson.los
bordesenAestnalasombra,y.u/Esunbordedeluzquecruzalas.ScorteV
S/.Elborde.xa/es
unaventajasobrelatrayectoriasimplenicapdesdeuhastaenT.ParaformarunrboldeexpansinmnimaT0que
contiene.u/,Quitarelborde.xa/desdeTyaadirelborde.u/.

PeroTesunrboldeexpansinmnimo,porloqueWT/unWT0/Porlotanto,T0debeseruna
rboldeexpansinmnimatambin.
Quedapordemostrarque.u/EsenrealidadunbordeseguroparaA.TenemosunT0,
Unpuestounacamisetay.xa/62APorlotanto,A[fu/GaT0.Enconsecuencia,puestoqueT0esuna
rboldeexpansinmnimo,.u/EsseguroparaA.

Teorema23.1nosdaunamejorcomprensindelfuncionamientodelGENERIC
MSTmtodoenungrficoconectadoGD.VE/.Comoelmtodopasa,la
Unconjuntoessiempreacclicodeotromodo,unrboldeexpansinmnimoincluyendounaspirante
contenerunciclo,queesunacontradiccin.Encualquiermomentodelaejecucin,elgrfico
GAD.VA/esunbosque,ycadaunodeloscomponentesconectadosdeGAesunrbol.
(Algunosdelosrboles:algunoscontienenslounvrtice,comoeselcaso,porejemplo,cuando
Elmtodocomienza:AestvacoyelbosquecontieneJVrbolesj,unoparacada
vrtice)Porotraparte,cualquierborde.useguro./AseconectaacomponentesdistintosdeGA,
yaqueA[fu/Gdebeseracclico.
Eltiempodebucledelaslneas24deGENERICMSTejecutajVj1vecesporque
seencuentraunodelosjVj1aristasdeunrboldeexpansinmnimoencadaiteracin.
Alprincipio,cuandoAD,hayJVrbolesjenGA,yquecadaiteracinreduce
nmeroen1.Cuandoelbosquecontieneunsolorbol,elmtodotermina.
LosdosalgoritmosenlaSeccin23.2utilicelasiguientecorolarioalteorema23.1.

Pgina50

23.1Elcrecimientodeunrboldeexpansinmnimo 629

corolario23.2
DejeGD.VE/ungrafoconectado,nodirigidoconunpesodevalorrealfuncin
wcindefinidaenE.SeaAunsubconjuntodeEqueseincluyeenalgunamnimo
rboldeexpansinparaG,ydejarCD.VCEC/seauncomponenteconectado(rbol)enel
bosqueGAD.VUN/.Situ/EsunbordedelaluzdeconexinCaalgnotrocomponente
enGA,acontinuacin,.u/EsseguroparaA.

PruebaElcorte.VCV VC/Arespeta,y.u/Esunaventajaligeraparaestecorte.
Porlotanto,.u/EsseguroparaA.

Ceremonias

23,11
Dejarte/SerunaventajamnimadepesoenungrafoconexoG.Demostrarque.U/
perteneceaunrboldeexpansinmnimodeG.

23,12
ProfesorSabatierconjeturalosiguienteinversodelteorema23.1.dejeGD
.VE/serungrafoconexo,nodirigidoconunafuncindeponderacindevalorrealwde
multadoenE.SeaAunsubconjuntodeEqueseincluyeenalgunosdeexpansinmnimo
rbolparaG,deje.SV S/sercualquiercortedeGquerespeteA,ydejarque.u/Serunseguro
EDGEparaA.SdecruceV S/.Elnu/Esunaventajaligeraparaelcorte.Muestraesa
Laconjeturadequeelprofesoresincorrecta,dandouncontraejemplo.

23,13
Demostrarquesiunborde.u/Estcontenidaenunrboldeexpansinmnimo,entonceses
unbordedeluzquecruzaalgunacortedelagrfica.

23,14
Darunejemplosencillodeungrficoconectadodetalmaneraqueelconjuntodearistasfu/W
existeuncorte.SV S/talque.u/Esunaluzdecruce.SbordeV S/g
noformaunrboldeexpansinmnimo.

23,15
SeaEunbordepesomximoenalgnciclodegrafoconexoGD.VE/.
DemostrarqueexisteunrboldeexpansinmnimodeG0D.Vmi
FEG/quetambinesuna

https://translate.googleusercontent.com/translate_f 31/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
rboldeexpansinmnimodeG.Esdecir,hayunrboldeexpansinmnimodeGque
noincluyee.

Pgina51

630 Captulo23mnimoSpanningTrees

23,16
Mostrarungrficoquetieneunmnimonicorboldeexpansinsi,paracadacortedela
grfica,hayunaventajanicaluzquecruzaelcorte.Demostrarqueelrecproconoes
verdaderadandouncontraejemplo.

23,17
Argumentarquesitodoslospesosdelasaristasdeungrafosonpositivos,entoncescualquiersubconjuntodearistasque
conectatodoslosvrticesytieneunpesototalmnimodebeserunrbol.Darunejemplo
parademostrarquelamismaconclusinnosesiguesipermitimosquealgunospesossean
nopositiva.

23,18
SeaTunrboldeexpansinmnimodeungrafoG,yseaLlalistaordenadadela
lospesosdebordedeT.DemostrarqueparacualquierotrorboldeexpansinmnimoT0deG,el
listaLestambinlalistaordenadadelospesosdelasaristasdeT0.

23,19
SeaTunrboldeexpansinmnimodeungrficoGD.VE/,yseaV0seaunsubconjunto
deV.SeaT0seaelsubgrafodeTinducidaporV0,yseaG0seaelsubgrafodeG
inducidaporV0.DemostrarquesiT0seconecta,entoncesT0esunrboldeexpansinmnimo
deG0.

23,110
DadoungrafoGyunrboldeexpansinmnimoT,suponemosquedisminuimosla
pesodeunodelosbordesdeT.DemostrarqueTestodavaunrboldeexpansinmnimo
porG.Demaneramsformal,seaTunrboldeexpansinmnimodeGconpesosdelasaristas
dadaporlafuncindepesow.Elijauno.xbordea/2Tyunnmeropositivok,
ydefinirlafuncindepesow0por
(
Wu/ situ/.xa/a
w0.uD
wxa/ksi.u/D.xa/a:

DemostrarqueTesunrboldeexpansinmnimadeGconpesosdelasaristasdadasporW0.

23,111?
DadoungrafoGyunrboldeexpansinmnimoT,suponemosquedisminuimosla
pesodeunodelosbordesnoenT.Darunalgoritmoparaencontrarelmnimo
rboldeexpansinenelgrficomodificado.

Pgina52

23.2LosalgoritmosdeKruskalyPrim 631

23.2LosalgoritmosdeKruskalyPrim

Losdosalgoritmosderboldeexpansinmnimoquesedescribenenestaseccinseanalizandetenidamentelas
elmtodogenrico.Cadaunodeellosusanunareglaespecficaparadeterminarunbordeseguroenlalnea3
deGENERICMST.EnelalgoritmodeKruskal,elconjuntoAesunbosquecuyosvrticesson
todoslosdelagrficadada.ElbordeseguroaadidoaAessiempreunmnimopeso
EDGEenelgrficoqueconectadoscomponentesdistintos.EnelalgoritmodePrim,el
Seformaunconjuntodeunsolorbol.ElbordeseguroaadidoaAessiempreunaventajademenorpeso
conectarelrbolaunvrticenoenelrbol.

elalgoritmodeKruskal
elalgoritmodeKruskalencuentraunbordeseguroparaaadiralbosqueencrecimientomediantelabsqueda,detodos
losbordesqueconectanlosdosrbolesenelbosque,unborde.u/Demenorpeso.
SeaC1yC2denotanlosdosrbolesqueestnconectadospor.u/.Desde.u/debe

https://translate.googleusercontent.com/translate_f 32/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
seaunbordeligeroqueconecteC1aalgnotrorbol,Corolario23.2implicaque.u/
esunbordeseguroparaC1.ElalgoritmodeKruskalcalificacomounalgoritmovorazporque
encadapasoseaadealbosqueunbordedemenorpesoposible.
NuestraaplicacindelalgoritmodeKruskalescomoelalgoritmoparacalcular
componentesconectadosdelaSeccin21.1.Seutilizaunaestructuradedatosdisjuntosajustadoa
mantenervariosconjuntosdisjuntosdeelementos.Cadagruposecomponedelosvrticesdeunrbol
delbosqueactual.LaoperacinFINDSET.u/devuelveunelementorepresentativo
Delconjuntoquecontieneu.Porlotanto,podemosdeterminarsidosvrticesuy
pertenecenalmismorbolensayandosiFINDSET.u/FesigualaINDSET./.A
combinarrboles,elalgoritmodeKruskalllamaalaUNIONprocedimiento.

MSTKRUSKAL.Gw/
1dC
2paracadavrtice2G:V
3 MAKESET./
4ordenarlosbordesdeG:Eenordendecrecienteporpesow
5decadaborde.u/2G:E,tomadaenordennodecrecienteenpeso
6 SiFINDSET.u/FINDSET./
7 ADA[fu/gramo
8 UNION.U/
9deretornoUn

Lafigura23.4muestracmofuncionaelalgoritmodeKruskal.Lneas13inicializarelconjuntoA
paraelconjuntovacoycrearrbolesjJV,unaquecontienecadavrtice.Eldebucleenel
lneas58examinabordesenfuncindesupeso,demenoramayor.Ellazo

Pgina53

632 Captulo23mnimoSpanningTrees

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(un) un 11 yo 4 14 mi (segundo)
un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(do) un 11 yo 4 14 mi (re) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(mi) un 11 yo 4 14 mi (F) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(gramo)
un 11 yo 4 14 mi (marido)
un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

Figura23.4LaejecucindelalgoritmodeKruskalenelgrficodelaFigura23.1.bordessombreados
perteneceralaselvaUnsiendocultivada.Elalgoritmoconsideracadabordeenformaordenadaenpeso.
Unaflechaapuntahaciaelbordebajoconsideracinencadapasodelalgoritmo.Sielbordeseuneados
rbolesdistintosenelbosque,queseaadealaselva,fusionandoaslosdosrboles.

cheques,paracadaborde.u/,Siloscriteriosdevaloracinuypertenecenalamisma
rbol.Silohacen,entonceselborde.u/Nosepuedeagregaralaselvasincrear
unciclo,yelbordesedescarta.Delocontrario,losdosvrticespertenecenadiferentes
rboles.Enestecaso,lalnea7aadeelborde.u/AA,ylalnea8seunelosvrtices
enlosdosrboles.

Pgina54

https://translate.googleusercontent.com/translate_f 33/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

23.2LosalgoritmosdeKruskalyPrim 633

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(yo) un 11 yo 4 14 mi (J) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(K) un 11 yo 4 14 mi (L) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(metro)
un 11 yo 4 14 mi (norte)
un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

Figura23.4,continunuevasmedidasparalaejecucindelalgoritmodeKruskal.

EltiempodeejecucindelalgoritmodeKruskalparaungrficoGD.VE/depende
sobrecmoseimplementalaestructuradedatosinconexosset.Suponemosqueutilizamos
laaplicacindisjuntossetbosquedelaseccin21.3conelrangouninpory
heursticarutacompresin,yaqueeslaaplicacinmsrpidaasintticamente
conocido.LainicializacindelconjuntoAenlalnea1tomaO.1/tiempo,yeltiempoparaordenarla
bordesenlalnea4eslaIgEOE/.(VamosatenerencuentaelcostedelaempresaconjuntajMAKESET
operacioneseneldebucledelaslneas23enunmomento.)Eldebucledelaslneas58
realizaOE/FINDSETyUNIONoperacionesenelbosquedisjuntosset.Alolargo
LaempresaconjuntaconjMAKESEToperaciones,stastienenuntotaldeO..VCE/.V//tiempo,
dondeeslafuncindecrecimientomuylentodefineenlaSeccin21.4.Porquenosotros
supongaqueGestconectado,tenemosjejjVj1,yporloqueeldisjuntossetoperacin
lastomanOE.V//tiempo.Adems,dadoque.jVj/DO.lgV/DO.lgE/,elTo
2,
TalmomentodeejecutarelalgoritmodeKruskalesOEIgE/.Alobservarquejej<jVj
tenemoslgjEjDO.lgV/,yaspodemoscitareltiempodeejecucindeKruskal
algoritmocomoOELGV/.

Pgina55

634 Captulo23mnimoSpanningTrees

AlgoritmodePrim
AligualqueelalgoritmodeKruskal,elalgoritmodePrimesuncasoespecialdelamineragenrica
MtododerbolesimoqueabarcadesdelaSeccin23.1.AlgoritmodePrimfuncionademaneramuy
aligualqueelalgoritmodeDijkstraparaencontrarcaminosmscortosenungrfico,queveremosenel
Seccin24.3.AlgoritmodePrimtienelapropiedaddequelosbordesenelconjuntoAsiempre
formarunsolorbol.ComomuestralaFigura23.5muestra,elrbolcomienzaapartirdeunarazarbitraria
vrticerycrecehastaqueelrbolseextiendeportodoslosvrticesenV.Cadapasosesumaala
UnrboldeunbordedeluzqueconectalaAaunaaisladavrticeyunoenelquehayunborde
deAesincidente.PorCorolario23.2,estareglasloaadebordesquesonsegurosparaA
Porlotanto,cuandoelalgoritmotermina,losbordesenformadeunaexpansinmnimo
rbol.Estaestrategiacalificacomocodiciosoyaqueencadapasoseaadealrboldeunborde
queaportalacantidadmnimaposibleelpesodelrbol.
ConelfindeimplementarelalgoritmodePrimeficiente,necesitamosunaformarpidaparaseleccionar
unnuevobordeparaagregaralrbolformadoporlosbordesenA.Enelpseudocdigoacontinuacin,
elgrficoconectadoGylarazrdelrboldeexpansinmnimoparasercultivadas
sonentradasalalgoritmo.Durantelaejecucindelalgoritmo,todoslosvrticesque
estnnoenelrbolderesidirenunacoladeprioridadminQbasadoenunaclavedeatributo.por
cadavrtice,elatributo:claveeselpesomnimodecualquierbordedeconexin
aunvrticeenelrbolporconvencin,:teclaD1sinoexistetalventaja.El
deatributos:losnombresdelospadresenelrbol.Elalgoritmomantieneimplcitamente
elconjuntoAdeGENERICMSTcomo
ADf.:/W2V FRGQg:

Cuandoelalgoritmotermina,lacoladeprioridadminQestvacaelmnimo
UnrboldeexpansinparaGes,pues,
ADf.:/W2V frgg:

https://translate.googleusercontent.com/translate_f 34/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

MSTPRIM.Gwr/
1decada2uG:V
2 u:teclaD1
3 u:DNIL
4R:teclaD0
5QDG:V
6,mientrasqueQ
7 UDEXTRACTMEN.Q/
8 porcada2G:Adjoeu
9 si2QyWu/<:Clave
10 :Du
11 :TeclaDwu/

Pgina56

23.2LosalgoritmosdeKruskalyPrim 635

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(un) un 11 yo 4 14 mi (segundo)
un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(do) un 11 yo 4 14 mi (re) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(mi) un 11 yo 4 14 mi (F) un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7 8 7
segundo do re segundo do re
4 9 4 9
2 2
(gramo)
un 11 yo 4 14 mi (marido)
un 11 yo 4 14 mi
7 6 7 6
8 10 8 10
marido gramo F marido gramo F
1 2 1 2

8 7
segundo do re
4 9
2
(yo) un 11 yo 4 14 mi
7 6
8 10
marido gramo F
1 2

Figura23.5LaejecucindelalgoritmodePrimenelgrficodelaFigura23.1.Elvrticedelaraz
esun.bordessombreadassonenelrbolquesecultivan,yvrticesnegrossonenelrbol.Encadapasode
elalgoritmo,losvrticesenelrboldedeterminaruncortedelagrfica,yunbordedeluzquecruzaelcorte
seaadealrbol.Enelsegundopaso,porejemplo,elalgoritmotieneunaopcindeaadircualquiera
.bbordec/oborde.ah/alrbolyaqueambossonbordesdeluzquecruzanelcorte.

Pgina57

636 Captulo23mnimoSpanningTrees

Lafigura23.5muestracmofuncionaelalgoritmodePrim.Lneas15establecerlaclavedecada
vrticea1(aexcepcindelarazr,cuyaclaveseestableceen0demaneraqueserel
primervrticeprocesado),establecelospadresdecadavrticeaNIL,einicializarlaminera
prioridaddelacolaQparacontenertodoslosvrtices.Elalgoritmomantienelasiguiente
invariantesdebucledetrespartes:
Antesdecadaiteracindeltiempodebucledelaslneas611,
1.ADf.:/W2V FRGQg.
https://translate.googleusercontent.com/translate_f 35/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
2.Losvrticesyacolocadosenelrboldeexpansinmnimosonaquellasenlas
V Q.
3.Paratodoslosvrtices
2Q,si:NIL,entonces:tecla<1y:clavees
elpesodeunbordedelaluz.:/Conexinaalgunosvrticeya
secolocaenelrboldeexpansinmnimo.

Lnea7identificaunvrticeuincidente2Qenunbordedelaluzqueatraviesaelcorte
.V QQ/(conlaexcepcindelaprimeraiteracin,enelqueuDrdebidoalalnea4).
ExtraccinudesdeelconjuntoQagregaalconjuntoV Qdevrticesenelrbol,porlotanto
aadiendo.uu:/aA.Eldebucledelaslneas811actualizalaclaveylosatributos
decadavrticeadyacenteauperonoenelrbol,manteniendodeesemodolatercera
partedelainvariantedebucle.
EltiempodeejecucindelalgoritmodePrimdependedecmoseimplementalaminera
prioridaddelacolaQ.SiponemosenprcticacomounQminpilabinaria(vaseelcaptulo6),que
puedeutilizarelBUILDMENHEAPprocedimientoparallevaracabolaslneas15enOV/hora.El
cuerpodeltiempobucleseejecutaJVjveces,ydadoquecadaEXTRACTMENoperacin
latomaO.lgV/hora,eltiempototaldetodaslasllamadasaEXTRACTMENesOVLGV/.
Eldebucleenlneas811ejecutaOE/vecesentotal,yaquelasumadela
longitudesdetodaslaslistasdeadyacenciaes2jEj.Dentrodeladebucle,podemosaplicarel
pruebaparasermiembrodeQenlalnea9entiempoconstante,manteniendounpocoparacadavrtice
quedeterminasiesonoesenQ,ylaactualizacindelabrocacuandoseretiraelvrtice
deP.Laasignacinenlalnea11implicaunaimplcitaDECREASEKEYoperacin
cinenelminheap,queunbinariominheapapoyaenO.lgV/hora.As,
eltiempototalparaelalgoritmodePrimesOVLGVCELGV/DOELGV/,quees
asintticamenteelmismoqueparanuestraimplementacindelalgoritmodeKruskal.
PodemosmejorareltiempodeejecucinasintticadelalgoritmodePrimmedianteelusodeFi
montonesBonacci.Captulo19muestraquesiunmontndeFibonaccitieneelementosjJV,una
EXTRACTMENoperacintomaO.lgV/horaamortizadoyDECREASEKEY
operacin(paraponerenprcticalalnea11)llevaO.1/horaamortizado.Porlotanto,siutilizamosuna
FibonaccimontndeaplicarlacoladeprioridadQmin,eltiempodeejecucindePrim
algoritmomejoradeOECVLGV/.

Pgina58

23.2LosalgoritmosdeKruskalyPrim 637

Ceremonias
23,21
elalgoritmodeKruskalpuededevolverdiferentesrbolesdeexpansinparaelmismogrficodeentradaG,
dependiendodecmoserompelazoscuandolosbordesseclasificanenorden.Muestraesa
paracadarboldeexpansinmnimoTdeG,hayunamaneradeordenarlosbordesdeGen
elalgoritmodeKruskalparaqueelalgoritmovuelveT.

23,22
SupongamosquerepresentamoslagrficaGD.VE/comounamatrizdeadyacencia.Darun
sencillaaplicacindelalgoritmodePrimparaestecasoqueseejecutaenVO2/hora.

23,23
ParaungrficoescasaGD.VE/,dondejejD,.V/,eslaimplementacinde
AlgoritmodePrimconunmontndeFibonacciasintticamentemsrpidoqueelbinarioenheap
implementacin?Qupasaconungrficodensa,dondejejD,.V2/?Cmo
debenlostamaosjejyJVjestarrelacionadosalaaplicacindeFibonaccienheapa
asintticamentemsrpidoquelaaplicacinbinariaenheap?

23,24
Supongamosquetodoslospesosdebordeenungrficosonnmerosenterosenelintervalode1ajVj.
QutanrpidosepuedehacercorrerelalgoritmodeKruskal?Qupasasilospesosdelasaristasson
enterosenelrangode1aWparaalgunaconstanteW?

23,25
Supongamosquetodoslospesosdebordeenungrficosonnmerosenterosenelintervalode1ajVj.
QutanrpidosepuedehacercorrerelalgoritmodePrim?Qupasasilospesosdelasaristassonnmerosenteros
enelintervalode1aWparaalgunaconstanteW?

23,26?
Supongamosquelospesosdelasaristasenungrficosedistribuyenuniformementesobrelamedia
OE0intervaloabierto1/.Qualgoritmo,KruskaloPrim,Sepuedehacerdeejecucin
Msrpido?

23,27?
SupongamosqueungrafoGtieneunrboldeexpansinmnimoyacalculado.Cmo
rpidamentepodemosactualizarelrboldeexpansinmnimosiaadimosunnuevovrticey
aristasincidentesaG?

23,28
ProfesorBordenproponeunnuevoalgoritmodivideyvencersparacalcular
https://translate.googleusercontent.com/translate_f 36/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
rbolesdeexpansinmnimos,locualvadelasiguientemanera.DadaunagrficaGD.VE/,
particionarelconjuntoVdevrticesendosconjuntosV1yV2talquejV1jjVy2jdifieren

Pgina59

638 Captulo23mnimoSpanningTrees

alosumo1.SeaE1comoelconjuntodearistasqueincidensloenvrticesenV1,y
seaE2elconjuntodearistasqueincidensloenvrticesenV2.recursivaresolver
unproblematreeexpansinmnimoencadaunodelosdossubgraphsG1D.V1E1/
yG2D.V2E2/.Porltimo,seleccioneelbordemnimodepesoenEqueatraviesael
cortar.V1V2/,yelusodeestebordeparaunirlosdosrbolesdeexpansinmnimosresultantes
enunnicorboldeexpansin.
Decualquierargumentanqueelalgoritmocalculacorrectamenteunrboldeexpansinmnimo
deG,oproporcionarunejemploparalosquefallaelalgoritmo.

Problemas

231segundamejorrboldeexpansinmnimo
DejeGD.VE/serungrafonodirigido,conectadocuyafuncinesdepeso
wWE!R,ysupongamosquetodoslospesosdelasaristasjejjVjysondistintos.
Sedefineunsegundomejorrboldeexpansinmnimadelasiguientemanera.SeaTelconjunto
detodoslosrbolesdeexpansindeG,yseaT0seaunrboldeexpansinmnimodeG.Entonces
unasegundamejorrboldeexpansinmnimoesunrbolqueatraviesaTtalesqueWT/D
minT 2TfT gfw.T00/g.
00 0

a.Demostrarqueelrboldeexpansinmnimoesnico,peroquelasegundamejormini
rboldeexpansinmadrenotieneporqusernico.

segundo.SeaTelrboldeexpansinmnimodeG.DemostrarqueGcontienebordes
.u/2Ty.xy/62TtalqueT fu/G[fxa/gesunsegundomejor
rboldeexpansinmnimodeG.

do.SeaTunrboldeexpansindeGy,paracualquierpardevrticesu2V,ymuchomaxoeu
denotarunaventajadepesomximoenlatrayectoriasimplenicaentreuy
enT.DescribirunVO2algoritmo/tiempoque,dadaT,calculamaxoeupara
todoslosu2V.

re.Darunalgoritmoeficienteparacalcularlasegundamejorrboldeexpansinmnimo
deG.

232rboldeexpansinmnimoengrafosdispersos
ParaungrficoconectadomuyescasaGD.VE/,podemosmejoraranmsenel
OECVLGV/tiempodefuncionamientodelalgoritmodePrimconmontonesdeFibonacciporprepro
procesamientoGparareducirelnmerodevrticesantesdeejecutarelalgoritmodePrim.En
enparticular,seelige,paracadavrticeu,elbordemnimopeso.u/incidente
enu,yponemos.u/Enelrboldeexpansinmnimoenconstruccin.Nosotros

Pgina60

Losproblemasrelacionadosconelcaptulo23 639

acontinuacin,contratartodoslosbordesseleccionados(vaselaSeccinB.4).Envezdecontraerestas
bordesdeunoalavez,enprimerlugaridentificarparesdevrticesqueseunenenelmismo
nuevovrtice.Entoncessecrealagrficaquehabraresultadodelacontratacin
estosbordesdeunoenuno,perolohacemospor"cambiodenombre"bordesacuerdoconlosconjuntos
enelquesecolocaronsuspuntosfinales.Variosbordesdelagrficaoriginalpuede
cambiarelnombredelamismacomolosdems.Entalcaso,slounoResultadosdeborde,ysu
pesoeselmnimodelospesosdelosbordesoriginalescorrespondientes.
Inicialmente,nosfijamoselmnimoTrboldeexpansinestconstruyendoestarvaco,
yparacada.Uborde/2E,deinicializarlosatributos.U/:OrigD.u/
yt/:CDwu/.Usamoselorigatributoparareferenciarelbordedela
grficoinicialqueseasociaconunbordeenelgrficocontratado.Elatributoc
sostieneelpesodeunaarista,ydadoquelosbordessecontraen,loactualizamossegn
elesquemaanteriorparalaeleccindepesosdelasaristas.ElprocedimientoMSTREDUCEtoma
insumosGyT,ydevuelveungrficocontradoG0conatributosactualizadosorig0
yc0.ElprocedimientotambinseacumulabordesdeGeneldeexpansinmnimo
rbolT.

MSTREDUCE.GT/
1decada2G:V

https://translate.googleusercontent.com/translate_f 37/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
2 :MarcaDFALSO
3 MAKESET./
4paracadau2G:V
5 siu:marca==FALSO
6 elegir2G:Adjoeutalque.u/:Cseminimiza
7 UNION.U/
8 TDT[fu/:Origg
9 u:marcaD:marcaDTRUE
10G0:VDssINDSET./W2G:Vg
11G0:ED
12paracada.xy/2G:E
13 TDFINDSET.x/
14 DFINDSET.y/
15 si.u/62G0:E
diecisis G0:EDG0:E[fu/gramo
17 .u/:Orig0D.xa/a:orig
18 .u/:C0D.xa/a:c
19 mssi.xa/a:c<.u/:c0
20 .u/:Orig0D.xa/a:orig
21 .u/:C0D.xa/a:c
22listasdeadyacenciaconstructoG0:AdjparaG0
23deretornoG0yT

Pgina61

640 Captulo23mnimoSpanningTrees

a.SeaTelconjuntodearistasdevueltosporMSTREDUCE,yseaAlamnima
rboldeexpansindelagrficaG0formadoporlallamadaMSTPRIM.G0c0r/,dondec0
eselatributodepesoenlosbordesdeG0:EyRescualquiervrticeenG0:V.Probar
queT[fxa/a:orig0W.xy/2AgesunrboldeexpansinmnimadeG.

segundo.ArgumentarquejG0:VjjVj=2.

do.MostrarcmoimplementarMSTREDUCEparaqueseejecuteenOE/hora.(Pista:
Utilizarestructurasdedatossimples.)

re.SupongamosquenosencontramoskfasesdelMSTREDUCE,utilizandolasalidaG0producido
porunafasecomolaentradaGalasiguientefaseylosbordesqueseacumulanenT.
ArgumentanqueeltiempototaldefuncionamientodelasfaseskesO.kE/.

mi.SupongamosquedespusdeejecutarkfasesdelMSTREDUCE,comoenlaparte(d),secorre
AlgoritmodePrimllamandoMSTPRIM.G0c0r/,dondeG0,conunpesoAT
homenajec0,esdevueltoporlaltimafaseyrescualquiervrticeenG0:V.Enseacomo
pararecogerkparaqueeltiempototaldefuncionamientoesOElgLGV/.Argumentarquesu
eleccindekminimizaeltiempodefuncionamientoglobalasinttica.

F.Paraquvaloresdejej(entrminosdejVj)haceelalgoritmodePrimconpreprocess
ingasintticamentesuperarelalgoritmodePrimsinprocesamientoprevio?

233Cuellodebotelladerboldeexpansin
UnrboldecuellodebotellaqueabarcaTdeungrafonodirigidoGesunrboldeexpansindeG
cuyamayorpesobordeesmnimosobretodoslosrbolesdeexpansindeG.decimosque
elvalordelarboldeexpansincuellodebotellaeselpesodelmximopeso
EDGEenT.

a.Argumentanqueunrboldeexpansinmnimoesunrboldeexpansincuellodebotella.

Laparte(a)muestraquelabsquedadeuncuellodebotellarboldeexpansinnoesmsdifcilqueencontrar
unrboldeexpansinmnimo.Enlaspartesrestantes,vamosamostrarcmoencontraruna
cuellodebotelladelrboldeexpansineneltiempolineal.

segundo.DarunalgoritmodetiempolinealquedaunagrficaGyunnmeroenterob,determina
sielvalordelrbolcuellodebotellaqueabarcaescomomximob.

do.Utiliceelalgoritmoparalaparte(b)comounasubrutinaenunalgoritmodetiempolinealpara
elproblemadecuellodebotellaspanningtree.(Pista:Esposiblequedeseeutilizarunasubrutina
queloscontratosconjuntosdebordes,comoenelMSTREDUCEprocedimientodescritoenel
Problema232).

Pgina62

Notasparaelcaptulo23 641

https://translate.googleusercontent.com/translate_f 38/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
234algoritmosspanningtreemnimoalternativo
Enesteproblema,nosdamospseudocdigoparatresalgoritmosdiferentes.Cadaunotoma
ungrafoconexoyunafuncindepesocomoentradaydevuelveunconjuntodearistasT.por
cadaalgoritmo,obienprobarqueTesunrboldeexpansinmnimooprobarqueTes
Nounrboldeexpansinmnimo.Tambindescribenlaimplementacinmseficientede
cadaalgoritmo,siesonocomputaunrboldeexpansinmnimo.
a.MaybeMSTAGw/
1clasificarlosbordesenordennocrecientedelospesosdelasaristasw
2TDE
3paracadaaristae,tomadaconelfindenocrecienteenpeso
4 siT FEGesungrafoconexo
5 TDT FEG
6deretornoT

segundo.MaybeMSTBGw/
1TD
2paracadaaristae,tomadaenordenarbitrario
3 siT[FEGnotieneciclos
4 TDT[FEG
5deretornoT

do.MaybeMSTCGw/
1TD
2paracadaaristae,tomadaenordenarbitrario
3 TDT[FEG
4 SiTtieneunciclodec
5 SeaE0seaunbordepesomximodec
6 TDT Fe0g
7deretornoT

Lasnotasdecaptulos

Tarjan[330]examinaelproblemaspanningtreemnimoyproporcionaunaexcelente
materialavanzado.GrahamyelInfierno[151]compilaronunahistoriadelamnimo
problemaspanningtree.
Tarjanatribuyeelprimeralgoritmoderboldeexpansinmnimoaunpapelde1926por
O.Boruvka.ElalgoritmodeBoruvkaconsisteencorrerO.lgV/iteracionesdel

Pgina63

642 Captulo23mnimoSpanningTrees

procedimientoMSTREDUCEdescritoenelproblema232.ElalgoritmodeKruskalera
reportadoporKruskal[222]en1956.ElalgoritmoconocidocomnmentecomoPrim
algoritmofuedehechoinventadoporPrim[285],perotambinfueinventadoanteriormentepor
V.Jarniken1930.
Laraznsubyacenteporalgoritmosvoracessoneficacesenlabsquedademnimos
rbolesdeexpansinesqueelconjuntodelosbosquesdeungrficoquerepresentaunamatroidgrfico.(Ver
Seccin16.4).
CuandojejD.VLGV/,elalgoritmodePrim,implementadoconmontonesdeFibonacci,
correenOE/hora.Paragrficosdispersas,utilizandounacombinacindelasideasde
AlgoritmodePrim,elalgoritmodeKruskal,yelalgoritmodeBoruvka,juntoconAd
estructurasdedatosavanzadas,FredmanyTarjan[114]danunalgoritmoqueseejecutaen
OELGV/hora.Gabow,Galil,Spencer,yTarjan[120]mejorestealgo
rithmseejecuteenOElglgV/hora.Chazelle[60]daunalgoritmoqueseejecuta
enOEy.EV//tiempo,dondey.EV/eslainversafuncionaldeAckermann
funcin.(VerlasnotasdecaptuloparaelCaptulo21paraunabrevediscusindeAckerman
LafuncindeMannysuinversa.)Adiferenciadeanterioresalgoexpansinmnimarbol
ritmos,elalgoritmodeChazellenosigueelmtodocodicioso.
Unproblemarelacionadoeslaverificacinspanningtree,enelquesenosdaungrfico
GD.VE/TyunrbolaE,ydeseamosdeterminarsiTesunmnimo
rboldeexpansindeG.Rey[203]daunalgoritmodetiempolinealparaverificarunspanning
rbol,basndoseeneltrabajoanteriordeKomls[215]yDixon,RauchyTarjan[90].
Losalgoritmosanterioressontodosdeterministaycaenenlacomparacindebase
modelodescritoenelcaptulo8.Karger,Klein,yTarjan[195]danunensayoclnicoaleatorizado
algoritmodemnimospanningtreequeseejecutaeneltiempoOVCE/esperada.Esta
algoritmoutilizarecursindeunamanerasimilaralalgoritmodeseleccindetiempolineal
enlaSeccin9.3:unallamadarecursivaenunproblemaauxiliaridentificaunsubconjuntodela
bordesE0quenopuedeestarencualquierrboldeexpansinmnimo.Otrallamadarecursiva
uno E0continuacin,seencuentraelrboldeexpansinmnimo.Elalgoritmotambinutilizalasideas
delalgoritmodeBoruvkayelalgoritmodereyparalaverificacindelrboldeexpansin.
FredmanyWillard[116]mostrcmoencontrarunrboldeexpansinmnimaen
OVCE/tiempousandounalgoritmodeterministaquenoestbasadaenlacomparacin.Su
https://translate.googleusercontent.com/translate_f 39/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
algoritmoasumequelosdatossonnmerosenterosbbitsyquelamemoriadelordenador
secomponedepalabrasdireccionablesbbits.

Pgina64

24 Fuentenicaderutasmscortas

ProfesorPatrickdeseaencontrarlarutamscortaposibledePhoenixaindicaciones
anapolis.DadounmapadecarreterasdelosEstadosUnidosenelqueladistanciaentre
cadapardeinterseccionesadyacentesestmarcado,cmopuededeterminarestomscorto
ruta?
UnaformaseraposibleenumerartodaslasrutasdesdePhoenixaIndi
anapolis,sesumanlasdistanciasencadaruta,yseleccionarelmscorto.Esfcil
vase,sinembargo,quelasrutasqueanularainclusoquecontienenciclos,elprofesorPatrick
Habraqueanalizarungrannmerodeposibilidades,lamayoradeloscualesson
simplementenovalelapenaconsiderar.Porejemplo,unarutadePhoenixaIndianapolis
quepasaatravsdeSeattleesobviamenteunamalaeleccin,porqueesdevariosSeattle
cientosdemillasfueradelcamino.
Enestecaptuloyenelcaptulo25,semuestralaformaderesolverestetipodeproblemasesfuerzo
cientemente.Enunproblemacaminosmscortos,senosdaungrafodirigidoponderado
GD.VE/,conlafuncindepesowWE!Rmapeobordesabienesdevalor
PesosElpesowp/pdelatrayectoriaDh01:::kieslasumadelospesos
desusbordesconstituyentes:
xK
wp/D w.i1i/:
ID1
Sedefineelpesoderutamscorta.u/Desdeuhastapor
(
pag
minfw.p/Wu gsihayuncaminodeua
.u/D
1 deotromodo:
UncaminomscortodesdeelvrticealvrticeusedefineentoncescomocualquiertrayectoriaPconelpeso
.uwp/D/.
EnelejemplodePhoenixaIndianapolis,podemosmodelodelahojaderutaenformadegrfico:
vrticesrepresentanlasintersecciones,bordesrepresentansegmentosdecarreteraentreinterseccin
ciones,ypesosdelasaristasrepresentanlasdistanciasporcarretera.Nuestroobjetivoesencontraruncaminomscorto
apartirdeunainterseccindadoenPhoenixaunainterseccindadoenIndianpolis.

Pgina65

644 Captulo24cortasdeorigennicoCaminos

pesosdelasaristaspuedenrepresentarmtricasdistintasdelasdistancias,comoeltiempo,costo,
sanciones,prdida,ocualquierotracantidadqueseacumulalinealmentealolargodeuncaminoy
quenosgustaraminimizar.
Elalgoritmoprimeroenamplitudenlabsquedadelaseccin22.2esunamscortacaminosalgo
rithmquefuncionaenlosgrficosnoponderadas,esdecir,losgrficosenlaquecadabordetieneunidad
peso.Debidoaquemuchosdelosconceptosdebsquedaenanchurasurgenenelestudio
derutasmscortasengrafosponderados,esposiblequedeseerevisarlaSeccin22.2antes
proceder.

Variantes

https://translate.googleusercontent.com/translate_f 40/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Enestecaptulo,noscentraremosenelproblemadeunasolafuentemscortacaminos:dada
unagrficaGD.VE/,queremosencontrarunarutamscortadesdeundeterminadoorigenvrtice
s2Vparacadavrtice 2V.Elalgoritmoparaelproblemadeunasolafuentepuede
resolvermuchosotrosproblemas,incluyendolassiguientesvariantes.

Singledestinomscortacaminosproblema:Encontraruncaminomscortoparaundeterminadodes
tinovrticetdesdecadavrtice.Porinversindeladireccindecadabordeen
lagrfica,podemosreduciresteproblemaaunproblemadeunasolafuente.
Deunsoloparproblemadelcaminomscorto:Encontraruncaminomscortodesdeuhastaparadeterminada
vrticesuy.Siresolvemoselproblemadeunasolafuenteconfuentedevrticeu,
resolvemosesteproblematambin.Porotraparte,todoslosalgoritmosconocidosparaesteproblema
tenerelmismocasopeortiempodeejecucinasintticacomolamejorfuentenica
Algoritmos
Todosoporparesmscortacaminosproblema:Encontraruncaminomscortodesdeuhastaparacadapar
devrticesuy.Apesardequepodemosresolveresteproblemamediantelaejecucindeunasola
algoritmodefuentedeunavezdesdecadavrtice,queporlogeneralpuederesolvermsrpido.Adems
nalmente,suestructuraesinteresanteporderechopropio.Captulo25tratalas
todoslosparesdeproblemaendetalle.

subestructuraptimadeuncaminomscorto

CaminosmscortosalgoritmosnormalmentesebasanenlapropiedaddequeuncaminomscortoBE
tweendosvrticescontieneotroscaminosmscortosdentrodeella.(ElEdmondsKarp
algoritmodeflujomximoenelcaptulo26tambinsebasaenestapropiedad.)Recall
subestructuraptimaqueesunodelosindicadoresclavequelaprogramacindinmica
(Captulo15)yelmtodocodicioso(Captulo16)podraaplicarse.goritmodeDijkstra
rithm,queveremosenlaSeccin24.3,esunalgoritmovoraz,ylaFloyd
Warshallalgoritmo,queencuentracaminosmscortosentretodoslosparesdevrtices(ver
Seccin25.2),esunalgoritmodeprogramacindinmica.Lossiguientesestadoslemma
lapropiedadptimosubestructuradeloscaminosmscortosconmayorprecisin.

Pgina66

Captulo24cortasdeorigennicoCaminos 645

Lema24.1(subtrazadosdecaminosmscortossonloscaminosmscortos)
Dadounponderado,grficodirigidoGD.VE/conlafuncindepesowWE!R,
seapDh01:::kiseruncaminomscortodesdeelvrtice0alvrticeky,paracualquier
iyjtalque0aiajk,seapijDhiIC1:::jielsubtrazadodep
desdeelvrticeialvrticej.Entonces,pijesunarutamscortadesdeiaj.

PruebaSidescomponemoslatrayectoriaPa p
yo0
0i pJ
ij p
k,entoncestenemosque
jk

wp/wpD0i/Cwpij/Cwpjk/.Ahora,supongamosquehayuncaminop0
ijdei
ajconelpesowp0 yo p
p
0i Ij
J
0 p
kesuncaminodesde0
jk

ij/<wpij/.Entonces, 0
parakcuyopesowp0i/Cw.p0 ij/Cw.pjk/esmenorquewp/,loquecontradice
elsupuestodequepesuncaminomscortodesde0ak.

bordesNegativopeso
Algunosejemplosdelproblemadeunasolafuentemscortacaminospuedenincluirbordes
cuyospesossonnegativos.SilagrficaGD.VE/nocontienenegativo
ciclosdepesoaccesibledesdelafuentes,acontinuacin,paratodos2V,elcaminomscorto
.speso/Restosbiendefinida,inclusositieneunvalornegativo.Sielgrfico
contieneunciclodepesonegativoaccesibledesdes,sinembargo,lospesosdelarutamscorta
noestnbiendefinidos.Nocaminodesaunvrticeenelciclopuedeseruncorto
rutaqueestsiempresepuedeencontraruncaminoconmenorpesosiguiendoelpropuesto
camino"mscorto"ydespusdeatravesarelciclodepesonegativo.Sihayunanegativo
ciclodepesoenalgncaminodesa,definimos.s/D1.
Lafigura24.1ilustraelefectodepesosnegativosypesonegativoci
culossobrepesosrutamscorta.Debidoaqueslohayuncaminodesauna(la
hsderutaai),tenemos.swsA/Da/D3.Demanerasimilar,slohayuncamino
desaB,yas.sb/wsDA/Cwab/D3C0,4/D1.Hay
infinitamentemuchoscaminosdesac:hsci,hsdoreci,hsdoredoreci,yassucesivamente.
DebidoaqueelciclodeHCdCItienepeso6C0,3/D3>0,larutamscortades
aCeshs,IC,con.spesowsC/Dc/D5.Delmismomodo,larutamscortades
adeshscdi,conelpeso.sd/Dwsc/Cw.cd/D11.Demaneraanloga,hay
unnmeroinfinitodecaminosdesene:hsei,hsmiFei,hsmiFmiFei,yporlo
en.DebidoaqueelciclodelFeitieneunpeso3C0,6/D3<0,sinembargo,hay
hayuncaminomscortodesdesae.AlrecorrerelciclodepesonegativoqueFEi
arbitrariamentemuchasocasionespodemosencontrarcaminosdesdeEconarbitrariamentegrandenegativo
pesos,yporlo.se/D1.Delmismomodo,.sf/D1.Debidoaquegesalcanzable
def,tambinpodemosencontrarcaminosconarbitrariamentegrandespesosnegativosdesag,
ytambieng/D1.Losvrticesh,i,j,ytambinformanunciclodepesonegativo.Ellos
nosonaccesiblesdesdes,sinembargo,yporlo.sh.s/DE/D.sj/D1.

https://translate.googleusercontent.com/translate_f 41/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina67

646 Captulo24cortasdeorigennicoCaminos

un segundo
3 4 1
marido yo
3 4 2
S do 6 re gramo
0 5 5 11 8 8 3
3
2 mi 3 F 7 J

6

Figura24.1pesosdelasaristasnegativasenungrafodirigido.Elpesoderutamscortadelafuentes
aparecedentrodecadavrtice.DebidoaquelosvrticesEyFformanunciclodepesonegativoaccesibledesdes,
quetienenlarutamscortadepesos1.Debidovrticegesaccesibledesdeunvrticecuyashortest
pesorutaes1,que,tambin,tieneunpesoderutamscortade1.LosvrticestalescomoH,IyJnoson
accesibledesdes,yporlotantosuspesosrutamscortason1,apesardequeseencuentranenunpesonegativo
ciclo.

Algunosalgoritmosmscortacaminos,talescomoelalgoritmodeDijkstra,asumenquetodos
pesosdelasaristasenelgrafodeentradasonnonegativos,comoenelejemplohojaderuta.Oth
ERS,talcomoelalgoritmoBellmanFord,permitirnegativopesobordesdelain
ponergrficoyproducirunarespuestacorrecta,siempreycuandonohayciclosdepesonegativoson
accesibledesdelafuente.Tpicamente,sihayunciclodetalpesonegativo,el
algoritmopuededetectareinformardesuexistencia.

Ciclos
Puedeuncaminomscortocontenerunciclo?Comoacabamosdever,nopuedeconteneruna
ciclodepesonegativo.Tampocopuedecontenerunciclodepesopositivo,yaqueremovible
ingelciclodelatrayectoriaproduceunatrayectoriaconlamismafuenteydestino
vrticesyunpesomsbajocamino.Esdecir,sipDh01:::kiesuncaminoy
cDhiIC1:::jiesunciclodepesopositivoenestecamino(demodoqueiDjy
wc/>0),entonceselcaminop0Dh01:::iJC1x2:::kitienepeso
wp0/Dwp/wc/</wp,yaspnopuedeserunarutamscortadesde0ak.
Esodejaslociclos0peso.Podemoseliminarunciclo0pesodecualquier
caminoparaproducirotrocaminocuyopesoeselmismo.Porlotanto,sihayunmscorto
caminodeunafuentedevrticesaunvrticededestinoquecontieneunciclode0peso,
luegohayotrocaminomscortodesdessinaesteciclo.Mientrasuna
caminomscortotieneciclos0peso,podemosextraervariasvecesestosciclosdela
caminohastaquetengamosuncaminomscortoqueeslibredeciclo.Porlotanto,sinprdidade
generalidadpodemossuponerquecuandoestamosencontrandocaminosmscortos,notienen
ciclos,esdecir,soncaminossencillos.DesdecualquierrutaacclicaenunagrficaGD.VE/

Pgina68

Captulo24cortasdeorigennicoCaminos 647

contieneenlamayoradelosvrticesdistintosjVj,tambincontieneenlamayoradeJVj1aristas.As,
podemosrestringirnuestraatencinalamscortadecaminosenlamayoradeJVj1aristas.

Enrepresentacindeloscaminosmscortos

Amenudodeseamosparacalcularlospesosnoslolarutamscorta,perolosvrticesencorto
estcaminostambin.Nosotrosrepresentamosaloscaminosmscortosdemanerasimilaralaformaenquerepresentamos
rbolesenamplitudenlaSeccin22.2.DadaunagrficaGD.VE/,mantenemospara
cadavrtice 2Vunantecesor:queesobienotrovrticeoNIL.El
Caminosmscortosalgoritmosdeestecaptuloseestablecenlosatributosdemodoquelacadenadepre
predecequeseoriginanenunvrticecorrehaciaatrsalolargodeunarutamscortadesa.
Porlotanto,dadounvrticeparaelque:NIL,elprocedimientoPRINTPATH.Gs/
delaseccin22.2,seimprimirunarutamscortadesa.
Enmediodelaejecucindeunalgoritmomscortacaminos,sinembargo,losvalorespodran
noindicanloscaminosmscortos.Aligualqueenlabsquedaenamplitud,vamosaestarinteresadoenel
predecesorsubgrafoGD.VE/inducidaporel valores.Unavezms,nos
definirelconjuntodevrticesVcomoelconjuntodevrticesdeGconnoNILpredecesores,
ademsdelossdeorigen:
FVD2VW:NILg[FSG:
ElconjuntodearistasdirigidasEeselconjuntodearistasinducidaporel
valoresdevrtices
enV:

https://translate.googleusercontent.com/translate_f 42/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
EDf.:/2EW2V FSGG:
Vamosademostrarquelosvaloresproducidosporlosalgoritmosenestecaptulotienen
lapropiedaddequeenlaterminacinGesun"rbolmscortacaminos"informally,unarraigado
quecontieneunarutamscortadesdelafuentesdecadavrticerbolqueesalcanzable
dels.UnrbolmscortacaminosescomoelrbolenamplituddelaSeccin22.2,pero
contienerutasmscortasdesdelafuentesedefineentrminosdepesosdelasaristasenlugarde
nmerodebordes.Paraserprecisos,ymuchoGD.VE/ungrafoponderado,dirigida
conlafuncindepesowWE!R,Gysesuponequenocontienepesonegativo
ciclosaccesibledesdeelvrticefuentes2V,demaneraqueloscaminosmscortosestnbien
definida.UnamscortacaminosderbolconrazensesunsubgrafodirigidoG0D.V0E0/,
dondeV0VyE0aE,detalmaneraque
1.V0eselconjuntodevrticesalcanzablesdesdesenG,
2.G0formaunrbolconrazs,y
3.2paratodosV0,elnicocaminosimpledesenelG0esunarutamscortades
enG.

Pgina69

648 Captulo24cortasdeorigennicoCaminos

T 6 x T 6 x T 6 x
3 9 3 9 3 9
3 3 3
2 1 4 2 7 2 1 4 2 7 2 1 4 2 7
S 0 S 0 S 0
5 3 5 3 5 3
5 11 5 11 5 11
6 6 6
Y Z Y Z Y Z
(un) (segundo) (do)

Figura24.2(a)conponderacin,grficodirigidoconpesosrutamscortadesdelafuentes.(b)La
bordessombreadosformanunrboldemscortacaminosarraigadaenlafuentes.(c)Otrorbolmscortacaminoscon
lamismaraz.

caminosmscortosnosonnecesariamentenico,ytampocolosonmscortosCaminosrboles.por
ejemplo,lafigura24.2muestraungrficodirigidoponderadoydosrbolesmscortosCaminos
conlamismaraz.

Relajacin
Losalgoritmosdeestecaptuloutilizanlatcnicaderelajacin.Paracadavrtice
2V,mantenemosunatributo:d,queesunlmitesuperiorenelpesode
uncaminomscortodelafuentesa.Llamamosa:dunaestimacindelarutamscorta.Nosotros
inicializarlasestimacionesdelarutamscortaypredecesoresporeltextosiguiente,.V/tiempo
procedimiento:

MeNITIALIZESINGLESUENTE.Gs/
1decadavrtice2G:V
2 :DD1
3 :DNIL
4s:dD0
Despusdelainicializacin,setiene:DNILparatodos2V,s:dD0,y:dD1para
2V FSG.
Elprocesoderelajarseunborde.u/Consisteencomprobarsipodemosmejo
demostrarelcaminomscortoparafundarloquevapasandoatravsdeuy,deseras,updat
ing:dy:.Unaetapaderelajacin1puededisminuirelvalordelarutamscorta

1Puedeparecerextraoqueeltrmino"relajacin"seutilizaparaunaoperacinqueaprietaunacotasuperior.
Elusodeltrminoeshistrico.Elresultadodeunaetapaderelajacinsepuedevercomounarelajacin
delarestriccin:dua:dCwu/,Que,porladesigualdadtriangular(Lema24.10),debeser
satisfechosiu:d.sDu/y:dD.s/.Esdecir,si:dUnU:dCwu/,Nohayuna"presin"
parasatisfacerestarestriccin,
porloquelarestriccines"relajado".

Pgina70

Captulo24cortasdeorigennicoCaminos 649

Usted V Usted V
5 2 9 5 2 6

RELAX(u,v,w) RELAX(u,v,w)
https://translate.googleusercontent.com/translate_f 43/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Usted V Usted V
5 2 7 5 2 6
(un) (segundo)

Lafigura24.3serelajaunborde.u/Conelpesowu/D2.Laestimacinderutamscortadecada
vrticeapareceenelvrtice.(a)Porque:d>u:dCwu/Antesdelarelajacin,elvalor
de:ddisminuye.(b)Acontinuacin,:dua:dCwu/Antesderelajarseelborde,porloquelaetapaderelajacin
Hojas:dsincambios.

estimacin:dypredecesordeactualizacin'satribuyen:.Elsiguientecdigoper
formaunaetapaderelajacinenelborde.u/EnO.1/hora:

RELAX.Uw/
1si:d>u:dCwu/
2 :DDT:dCwu/
3 :Du

Lafigura24.3muestradosejemplosderelajanteunborde,unaenlaqueunarutamscorta
estimacindisminuyeyunoenelquenohaycambiosenlasestimaciones.
CadaalgoritmoenestecaptulomellamaNITIALIZESINGLESUENTEyluegore
repetidamenterelajabordes.Porotraparte,larelajacineselnicomedioporelcualshortest
estimacionesdetrayectoriaypredecesorescambian.Losalgoritmosdeestecaptulodifierenen
cuntasvecesserelajancadabordeyelordenenqueserelajanbordes.Dijk
ElalgoritmodeStrayelalgoritmomscortacaminosparagrafosdirigidosacclicosrelajarse
cadaaristaexactamenteunavez.ElalgoritmoBellmanFordrelajacadabordejVj1
veces.

Propiedadesdelastrayectoriasmscortasyrelajacin
Paraprobarlosalgoritmosenestecaptulocorrecta,vamosaapelaravariosPROP
propiedadecaminosmscortosyrelajacin.Decimosestaspropiedadesaqu,ySeccin
cin24.5ellosdemuestraformalmente.Parasureferencia,cadapropiedadindicaaquin
incluyeellemaapropiadoonmerocorolariodelaSeccin24.5.Elltimo
cincodeestaspropiedades,queserefierenalasestimacionesdecaminomscortooelpredecesor
subgrafo,suponenimplcitamentequeelgrficoseiniciaconunallamadaalaINITIALIZE
SINGLESUENTE.Gs/yquelanicamaneradequelasestimacionesdelarutamscortayla
cambiopredecesorsubgrafosonporalgunasecuenciadepasosderelajacin.

Pgina71

650 Captulo24cortasdeorigennicoCaminos

Ladesigualdaddeltringulo(Lema24.10)
Paracualquier.uborde/2E,tenemos.s.s/au/Cwu/.
Propiedaddellmitesuperior(Lema24.11)
Siempretenemos:d es/2paratodoslosvrticesV,yunavezque:dlograel
.sdevalor/,Quenuncacambia.
Nopathpropiedad(Corolario24.12)
Sinohayuncaminodesa,entoncessiempretenemos:d.sD/D1.
Propiedaddeconvergencia(Lema24.14)
Sisu!EsuncaminomscortoenGporalgunau2V,ysiu:d.sDu/a
cualquiermomentoantesderelajante.Uborde/,Entonces:dD.s/Entodomomentodespus.
PropiedadPathrelajacin(Lema24.15)
SipDh01:::kiesuncaminomscortodesdesD0ak,yrelajarel
bordesdepenlaorden.01/.12/:::.k1k/,entoncesk:DD.sk/.
Estapropiedadsemantieneindependientementedecualquierotramedidaderelajacinqueseproducen,inclusosi
queseentremezclanconlasrelajacionesdelosbordesdep.
Propiedadsubgrafopredecesor(Lema24.17)
Unavez:DD.s/2Vparatodos,elsubgrafopredecesoresunamscortacaminos
rbolenraizadoenels.

Bosquejodelcaptulo
Seccin24.1presentaelalgoritmodeBellmanFord,queresuelveelorigennico
problemamscortacaminosenelcasogeneralenelquelosbordespuedentenerpesonegativo.
ElalgoritmoBellmanFordesmuysimple,ytienelaventajaadicional
dedetectarsiunciclodepesonegativoesaccesibledesdelafuente.Segundo
cin24.2daunalgoritmodetiempolinealparaelclculoderutasmscortasdeunsolo
fuenteenungrficoacclicodirigido.Seccin24.3cubreelalgoritmodeDijkstra,que
tieneuntiempodeejecucinmsbajoqueelalgoritmodeBellmanFord,perorequiereelborde
pesosparasernonegativo.Seccin24.4muestracmopodemosutilizarelBellmanFord
algoritmopararesolveruncasoespecialdelaprogramacinlineal.Porltimo,laSeccin24.5
demuestralaspropiedadesdeloscaminosmscortosyrelajacinindicadosanteriormente.
Requerimosalgunasconvencionesparahaceraritmticaconinfinitos.VamosaAS
https://translate.googleusercontent.com/translate_f 44/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Sumequeparacualquiernmeroreala1,tenemosunC1D1CunD1.Adems,para
hacernuestraspruebastienenenlapresenciadeciclosdepesonegativo,supondremos
queparacualquiernmeroreala1,tenemosunC.1/D.1/CaD1.
TodoslosalgoritmosdeestecaptulosuponenqueelgrafodirigidoGsealmacenaenel
larepresentacindeadyacencialista.Adems,sealmacenaconcadabordeessupeso,porlo
queamedidaqueserecorrecadalistadeadyacencia,podemosdeterminarlospesosdelasaristasenO.1/
tiempoporfilo.

Pgina72

24.1ElalgoritmoBellmanFord 651

24.1ElalgoritmoBellmanFord

ElalgoritmodeBellmanFordresuelveelorigennicodemscortacaminosproblemade
elcasogeneralenelquelospesosdebordepuedesernegativo.Dadounponderada,di
rectedgrficaGD.VE/sconlafuenteylafuncindepesowWE!R,la
AlgoritmodeBellmanForddevuelveunvalorbooleanoqueindicasihayono
unciclodepesonegativoqueesaccesibledesdelafuente.SihayunCytales
CLE,elalgoritmoindicaquenoexistesolucin.Sinohaytalciclo,el
algoritmoproduceloscaminosmscortosysuspesos.
Elalgoritmoserelajabordes,disminuyendoprogresivamenteunaestimacin:denel
pesodeunarutamscortadesdelafuentesdecadavrtice2Vhastaquesealcanza
los.spesoderutamscortareales/.ElalgoritmodevuelveTRUEsiyslosi
elgrficonocontieneciclosdepesonegativoquesonaccesiblesdesdelafuente.

BELLMANFORD.Gws/
1INITIALIZESINGLESUENTE.Gs/
2paraiD1aJG:Vj1
3 paracada.Uborde/2G:E
4 RELAX.Uw/
5decadaborde.u/2G:E
6 si:d>u:dCwu/
7 volverFALSO
8deretornoVERDADERO

Lafigura24.4muestralaejecucindelalgoritmoBellmanFordenungrfico
con5vrtices.Despusdeinicializareldy losvaloresdetodoslosvrticesenlalnea1,
elalgoritmohacejVj1pasaalolargodelosbordesdelagrfica.Cadapasoes
unaiteracindeldebucledelaslneas24yconsisteenrelajarcadabordedela
representargrficamenteunavez.Lasfiguras24.4(b)(e)muestraelestadodelalgoritmodespusdecadaunadelas
cuatropasadasatravsdelosbordes.DespusdehacerjVj1pasa,lneas58deverificacindeuna
ciclodepesonegativoydevuelveelvalorbooleanoapropiado.(Veremosunpoco
mstardeporqufuncionaestacomprobacin).
ElalgoritmoBellmanFordseejecutaentiempoO.VE/,yaquelainicializacinen
lnea1toma,.V/hora,cadaunodelosjVj1pasaalolargodelosbordesdelaslneas24
tomas,.E/hora,yladebucledelaslneas57detomaOE/hora.
ParademostrarlaexactituddelalgoritmoBellmanFord,comenzamosmostrandoque
sinohayciclosdepesonegativo,elalgoritmocalculalarutamscortacorrecta
pesosparatodoslosvrticesalcanzablesdesdelafuente.

Pgina73

652 Captulo24cortasdeorigennicoCaminos

T 5 x T 5 x T 5 x
2 6 2 6 2 4
6 6 6
3 3 3
S 0 8 S 0 8 S 0 8
4 7 4 7 4 7
7 2 7 2 7 2
7 7 2
Y 9 Z Y 9 Z Y 9 Z
(un) (segundo) (do)

T 5 x T 5 x
2 2 4 2 2 4
6 6
3 3
S 0 8 S 0 8
4 7 4 7
7 2 7 2

https://translate.googleusercontent.com/translate_f 45/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
7Y 9 2Z Y7 9 2
Z
(re) (mi)

Figura24.4LaejecucindelalgoritmoBellmanFord.Lafuenteeselvrtices.EldVal
UESaparecendentrodelosvrticesyaristassombreadasindicanvalorespredecesoras:sielborde.u/es
sombreada,entonces:Du.Enesteejemploparticular,cadapasadarelajalosbordesenelorden
.tx/.ta/a.t'/.xt/.yx/.y'/.'x/.'s/.st/.sa/a.(a)Lasituacinjustoantesdela
primeropasesobrelosbordes.(b)(e)Lasituacindespusdecadapasadasucesivasobrelosbordes.eld
y valoresenlaparte(e)sonlosvaloresfinales.ElalgoritmoBellmanForddevuelveTRUEeneste
ejemplo.

lema24.2
DejeGD.VE/ungrafoponderado,dirigidaconlafuentesyelpesofuncin
cinwWE!R,ysupongamosqueGnocontieneciclosdepesonegativoqueestn
accesibledesdes.Entonces,despusdelajVj1iteracionesdeladebucledelaslneas24
deBELLMANFORD,tenemos:d.sD/Paratodoslosvrticesquesonalcanzables
dels.

PruebaDemostramosellemaapelandoalapropiedadpathrelajacin.Estafa
Sidercualquiervrticequeesaccesibledesdes,yseapDh01:::ki,donde
0DsykD,sercualquiercaminomscortodesa.Debidoaquesonloscaminosmscortos
sencilla,ptieneenlamayoradelosbordesJVJ1,yporlokunaempresamixtaJ1.CadaunodelosjVJ1iteracin
cionesdeladebucledelaslneas24relajatodoslosbordesjej.Entrelosbordesderelajen
laiteracini,paraiD12:::k,es.i1i/.Porlapropiedadpathrelajacin,
Porlotanto,:DDk:DD.sk.s/D/.

Pgina74

24.1ElalgoritmoBellmanFord 653

corolario24.3
DejeGD.VE/ungrafoponderado,dirigidaconvrticefuentesypeso
funcinwWE!R,ysupongamosqueGnocontieneciclosdepesonegativoque
sonaccesiblesapartirdels.Entonces,paracadavrtice2V,hayuncaminodesasi
yslosiBELLMANFORDterminacon:d<1cuandoseejecutaenG.

LapruebaLapruebasedejacomoejercicio24,12.

Teorema24.4(correccindelalgoritmoBellmanFord)
SeaBELLMANFORDpuedeejecutarenunponderadagrfica,dirigidaGD.VE/con
sfuenteylafuncindepesowWE!R.SiGnocontieneciclosdepesonegativo
quesonaccesiblesdesdes,entonceselalgoritmodevuelveTRUE,tenemos:d.sD/
2V,yelsubgrafopredecesorGesunrboldemscortacaminos
paratodoslosvrtices
enraizadaens.SiGcontieneunciclodepesonegativoaccesibledesdes,entoncesel
algoritmodevuelveFALSO.

PruebaSupongamosquegrafoGnocontieneciclosdepesonegativoquesonREACH
poderdelafuentes.Enprimerlugar,demostrarlaafirmacindequeenlaterminacin,:DD.s/
paratodoslosvrticesV2.Sivrticeesaccesibledesdes,entonceselLema24.2demuestraesto
Reclamacin.Sinoesaccesibledesdes,entonceslaafirmacinsedesprendedelatpicarutasinPROP
ErtyPorlotanto,laafirmacinsedemuestra.Lapropiedadpredecesorsubgrafo,juntoconel
reclamacin,implicaqueGesunrboldemscortacaminos.Ahorausamoslapretensindedemostrarque
BELLMANFORDdevuelveTRUE.Alterminar,tenemosparatodoslosbordes.u/2E,
:DD.s/
.sAu/Cwu/(Porladesigualdadtriangular)
Du:dCwu/
yporlotantoningunadelaspruebasenlalnea6causaBELLMANFORDparavolverFALSO.Ah
primerplano,devuelveTRUE.
Ahora,supongamosquegrafoGcontieneunciclodepesonegativoqueesalcanzable
delafuentedesdejarqueestecicloseaCDh01:::ki,donde0Dk.Entonces,
xK
w.i1i/<0: (24.1)
ID1
SupongamosporelpropsitodelacontradiccindequelosrendimientosAlgoritmodeBellmanFord
TRUE.Porlotanto, i:d i1:dCw. i1 i/iDpara12:::Ksumandolos
lasdesigualdadesdetodoelciclocnosda

https://translate.googleusercontent.com/translate_f 46/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Pgina75

654 Captulo24cortasdeorigennicoCaminos

xK xK
i:d .i1:dCw.i1i//
ID1 ID1
xK xK
re i1:dC w.i1i/:
ID1 ID1
Desde
Pk 0Dk,encadavrticecapareceexactamenteunavezencadaunadelassumatorias
Pk
ID1i:dy ID1i1:d,yas
xK xK
i:dD i1:d:
ID1 ID1
Porotraparte,porelCorolario24.3,i:desfinitoparaiD12:::KAs,
xK
0A w.i1i/
ID1
loquecontradiceladesigualdad(24.1).LlegamosalaconclusindequeelalgoritmodeBellmanFord
devuelveTRUEsigrafoGnocontieneciclosdepesonegativoaccesibledesdela
fuente,yFALSOlocontrario.

Ceremonias

24,11
EjecutarelalgoritmodeBellmanFordenelgrafodirigidodelafigura24.4,utilizandoversin
tex'comolafuente.Encadapase,relajarsebordesenelmismoordenqueenlafigura,y
mostrarlady valoresdespusdecadapasada.Ahora,cambiarelpesodelborde.'x/
a4yejecutarelalgoritmodenuevo,usandoscomolafuente.

24,12
DemostrarCorolario24.3.

24,13
Dadounponderada,grficodirigidoGD.VE/sinciclosdepesonegativo,
SeaMelmximosobretodoslosvrtices2Vdelnmeromnimodebordes
enunarutamscortadesdelafuentesa.(Aqu,elcaminomscortoesenpeso,nose
elnmerodearistas.)sugierenuncambiosencilloparaelalgoritmodeBellmanFordque
permitequeseterminanenmC1pasa,inclusosimnoseconocedeantemano.

24,14
ModificarelalgoritmodeBellmanFordparaqueseestablece:da1paratodoslosvrticesde
quehayunciclodepesonegativoenalgncaminodesdelafuenteal.

Pgina76

24,2solafuenterutasmscortasengrafosdirigidosacclicos 655

24,15?
DejeGD.VE/una,grficodirigidoponderadoconlafuncindepesowWE!R.
DarunalgoritmoO.VE/timedeencontrar,paracadavrticeV2,elvalorI./D
minu2Vf.u/gramo.

24,16?
Supongamosqueunponderada,grficodirigidoGD.VE/tieneunciclodepesonegativo.
Darunalgoritmoeficienteparalistarlosvrticesdeunodedichosciclos.Demostrarquesu
algoritmoescorrecto.

24,2solafuenterutasmscortasengrafosdirigidosacclicos

Porlarelajacindelosbordesdeunadagponderada(grficoacclicodirigido)GD.VE/
deacuerdoaunaclasificacintopolgicadesusvrtices,podemoscalcularrutasmscortasdesde
unasolafuenteen,.VCE/hora.caminosmscortossonsiemprebiendefinidosenunDAG,
yaqueinclusosihaybordesdepesonegativo,puedennoexistenciclosdepesonegativo.
ElalgoritmocomienzaporlaclasificacintopolgicamenteelGDA(vaselaSeccin22.4)paramejo
representarunaordenacinlinealdelosvrtices.SielGDAcontieneunarutadesdeelvrticeupara
vrtice,entoncesuprecedeenlaclasificacintopolgica.Hacemosunsolopaseal
vrticesenelordentopolgicamenteordenados.Amedidaqueseprocesacadavrtice,nosrelajamoscada
aristaquesaledelvrtice.

DAGSHORTESTPATHS.Gws/
1ordenartopolgicamentelosvrticesdeG

https://translate.googleusercontent.com/translate_f 47/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
2MeNITIALIZESINGLESUENTE.Gs/
3decadavrticeu,tomadaconelfintopolgicamenteordenados
4 paracadavrtice2G:Adjoeu
5 RELAX.Uw/

Lafigura24.5muestralaejecucindeestealgoritmo.
Eltiempodeejecucindeestealgoritmoesfcildeanalizar.ComosemuestraenlaSeccin22.4,
laclasificacintopolgicadelalnea1toma,.VCE/hora.LaconvocatoriadelaINITIALIZE
SINGLESUENTEenlalnea2lleva,.V/hora.Eldebucledelaslneas35hacequeuno
iteracinporvrtice.Entotal,eldebucledelaslneas45serelajacadaaristaexactamente
unavez.(Hemosutilizadounanlisisagregadoaqu.)Debidoaquecadaiteracindel
interiordebuclefortoma,.1/hora,eltiempototaldeejecucines,.VCE/,queeslineal
eneltamaodeunarepresentacindeadyacencialistadelagrfica.
ElsiguienteteoremamuestraquelaDAGSHORTESTPATHSprocedimientocorrespondiente
tamentecalculalasrutasmscortas.

Pgina77

656 Captulo24cortasdeorigennicoCaminos

6 1 6 1
R S T x Y Z R S 2 T x Y Z
5 0
2 7 1 2 5 0 7 1 2
3 4 2 3 4 2
(un) (segundo)

6 1 6 1
R S T x Y Z R S T x Y Z
5 0
2
2
7
6
1 2 5 0
2
2
7
6
1
6
2
4
3 4 2 3 4 2
(do) (re)

6 1 6 1
R S T x Y Z R S T x Y Z
5 0
2
2
7
6
1
5
2
4 5 0
2
2
7
6
1
5
2
3
3 4 2 3 4 2
(mi) (F)

6 1
R S T x Y Z
5 0
2
2
7
6
1
5
2
3
3 4 2
(gramo)

Figura24.5Laejecucindelalgoritmodecaminosmnimosenungrficoacclicodirigido.El
vrticesestnordenadostopolgicamentedeizquierdaaderecha.Elvrticefuenteess.Losvaloresdedaparecen
dentrodelosvrtices,bordesysombreadosindicanlosvalores.(a)Lasituacinantesdelaprimeraiteracin
deladebucledelaslneas35.(b)(g)Lasituacindespusdecadaiteracindeladebucledelaslneas35.
Elvrticerecinennegrecidoencadaiteracinseutilizcomouenesaiteracin.Losvaloresquesemuestranen
parte(g)sonlosvaloresfinales.

teorema24.5
Siunponderada,grficodirigidoGD.VE/stienevrticefuenteynohayciclos,acontinuacin,
alaterminacindelaDAGSHORTESTPATHSprocedimiento,:d.sD/paratodos
2vrticesV,yelsubgrafopredecesorGesunrboldemscortacaminos.

PruebaPrimerodemostramosque:dD.s/Paratodoslosvrtices 2Venterminacin
Cin.Si noesaccesibledesdes,entonces:dD.s/D1porelsenderosin
propiedad.Ahora,supongamosqueesaccesibledesdes,porloquehayuncorto
esttrayectoriaPDh01:::ki,donde0DsykD.DebidoaquePRO

Pgina78

24,2solafuenterutasmscortasengrafosdirigidosacclicos 657

CESSlosvrticesenordentopolgicamenteordenados,nosrelajamoslosbordesdelapenel
orden.01/.12/:::.k1k/.Lapropiedadpathrelajacinimplicaque
i:dD.s i/enlaterminacindeiD01:::KFinalmente,porelpredecessor
Propiedadsubgrafo,Gesunrboldemscortacaminos.

Unaaplicacininteresantedeestealgoritmosepresentaenladeterminacindelasrutascrticas
eneldiagramaPERT2anlisis.Bordesrepresentanlostrabajosarealizar,ylospesosdelasaristas
https://translate.googleusercontent.com/translate_f 48/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
representarlostiemposrequeridospararealizartrabajosparticulares.Sielborde.u/Entraversin
texyborde.x/hojas,acontinuacin,.utrabajo/Debeserrealizadoantesdeltrabajo.x/.
Uncaminoatravsdeestedagrepresentaunasecuenciadepuestosdetrabajoquedebeserrealizadoenuna
ordenparticular.Unarutacrticaesunlargocaminoatravsdeldag,loquecorresponde
paraeltiempomslargoparallevaracabocualquiersecuenciadepuestosdetrabajo.Porlotanto,elpesodeuncrtico
rutaproporcionaunlmiteinferioreneltiempototalpararealizartodoslostrabajos.Podemosencontrar
unarutacrticaporcualquiera
lanegacindelospesosdelasaristasyenfuncionamientoDAGSHORTESTPATHS,o
corriendoDAGSHORTESTPATHS,conlamodificacindequereemplazamos"1"
por"1"enlalnea2delaINITIALIZESINGLESUENTEy">"por"<"enel
RELAXprocedimiento.

Ceremonias

24,21
EjecutarDAGSHORTESTPATHSenelgrafodirigidodelafigura24.5,usandovrticer
comolafuente.

24,22
Supongamosquecambiamoslalnea3delDAGSHORTESTPATHSparaleer

3paralosprimerosJVj1vrtices,tomadasconelfintopolgicamenteordenados

Demostrarqueelprocedimientoseguirasiendocorrecta.

24,23
ElgrficodePERTformulacindadaanteriormenteesalgopoconatural.Deunamaneramsnaturalmente
estructuraral,vrticesrepresentarapuestosdetrabajoylosbordesrepresentarasecuenciacin
restriccionesesdecir,.uborde/Indicaraqueeltrabajoudebellevarseacaboantes
trabajo.Entoncespodramosasignarpesosalosvrtices,aristasqueno.ModificarelDAG
SHORTESTPATHSprocedimientoparaqueencuentreuncaminomslargoenunacclicodirigido
grficoconvrticesponderadoseneltiempolineal.

2"PERT"esunacrnimode"Tcnicaderevisinyevaluacindeprogramas."

Pgina79

658 Captulo24cortasdeorigennicoCaminos

24,24
Darunalgoritmoeficienteparacontarelnmerototaldecaminosenunacclicodirigido
grafico.Analizarsualgoritmo.

24.3algoritmodeDijkstra

elalgoritmodeDijkstraresuelveelproblemadelacortasdeorigennicosenderosenunponderada,
grafodirigidoGD.VE/paraelcasoenelquetodoslospesosdelasaristassonnonegativos.
Enestaseccin,porlotanto,sesuponequewu/ 0paracadaborde.u/2E.Como
veremosmsadelante,conunabuenaaplicacin,eltiempodeejecucindelalgoritmodeDijkstra
esmenorqueladelalgoritmoBellmanFord.
elalgoritmodeDijkstramantieneunconjuntoSdevrticescuyaltimarutamscorta
pesosdelafuentesyahansidodeterminados.Elalgoritmoderepetibilidad
damenteseleccionaelvrticeu2VSconlaestimacinmnimaderutamscorta,aadeu
aS,yrelajatodoslosbordesdejandou.Enlasiguienteaplicacin,utilizamosuna
minprioridaddelacolaQdevrtices,cerradoporsusvaloresd.

DIJKSTRA.Gws/
1INITIALIZESINGLESUENTE.Gs/
2SD
3QDG:V
4,mientrasqueQ
5 UDEXTRACTMEN.Q/
6 SDS[GUB
7 paracadavrtice2G:Adjoeu
8 RELAX.Uw/

elalgoritmodeDijkstrarelajabordes,comosemuestraenlafigura24.6.Lalnea1seinicializa
lady Losvaloresdelaformahabitual,ylalnea2inicializaelconjuntoSalvaco
conjunto.ElalgoritmomantienelainvariantequeQDV Seneliniciodecada
iteracindeltiempodebucledelaslneas48.Lnea3inicializalacoladeprioridadminQ
paracontenertodoslosvrticesenVdesdeSDenesemomento,elinvarianteesciertodespusde
3.Cadalneadetiempoatravsdeltiempodebucledelaslneas48,lnea5extractosdeunvrticeu
QDVSylalnea6sesumaquefijeS,manteniendodeestamaneraelinvariante.(Elprimero
tiempoatravsdeestebucle,uDs.)Vertexu,porlotanto,tieneelmspequeodecaminomscorto

https://translate.googleusercontent.com/translate_f 49/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
estimacindecualquiervrticeenV
S.Acontinuacin,laslneas78relajarsecadaborde.u/Salidau,
actualizandoaslaestimacin:dyelpredecesor:sipodemosmejorarel
caminomscortoparaencontrarloquevapasandoatravsdeu.Observequeelalgoritmo
NuncaseinsertaenlosvrticesQdespusdelalnea3yquecadavrticeseextraedeQ

Pgina80

24.3algoritmodeDijkstra 659

T 1 x T 1 x T 1 x
10 8 14
10 10 10
S 0 2 3 9 4 6 S 0 2 3 9 4 6 S 0 2 3 9 4 6

5 7 5 7 5 7
5 5 7
Y 2 Z Y 2 Z Y 2 Z
(un) (segundo) (do)
T 1 x T 1 x T 1 x
8 13 8 9 8 9
10 10 10
S 0 2 3 9 4 6 S 0 2 3 9 4 6 S 0 2 3 9 4 6

5 7 5 7 5 7
5 7 5 7 5 7
Y 2 Z Y 2 Z Y 2 Z
(re) (mi) (F)

Figura24.6LaejecucindelalgoritmodeDijkstra.Lafuenteseselvrticemsalaizquierda.El
lasestimacionesdelarutamscortaaparecendentrodelosvrticesyaristassombreadasindicanvalorespredecesoras.
S.(a)La
vrticesnegrosestnenelconjuntoS,yvrticesblancosestnenlacoladeQDVminprioridad
situacinjustoantesdelaprimeraiteracindeltiempodebucledelaslneas48.Elvrticesombreadatienelamini
dvalormadreyseeligecomovrticeuenlalnea5.(b)(f)Lasituacindespusdecadaiteracinsucesiva
deltiempodebucle.Elvrticesombreadaencadaparteseeligecomouvrticeenlalnea5delasiguienteiteracin.
Losvaloresdedypredecesoresquesemuestranenlaparte(f)sonlosvaloresfinales.

yseaadeaSexactamenteunavez,demodoqueeltiempodebucledelaslneas48iteraexactamentejVj
veces.
DebidoaqueelalgoritmodeDijkstrasiempreeligeel"ligero"ovrtice"mscercano"
Env SparaagregaraestablecerS,decimosqueutilizaunaestrategiacodiciosa.Captulo16explica
lasestrategiasvoracesendetalle,peronoesnecesariohaberledoesecaptuloparacomprender
elalgoritmodeDijkstra.estrategiascodiciososnosiempreproducenresultadosptimosenlageneracin
eral,perocomoelsiguienteteoremaysudemostracincorolario,elalgoritmodeDijkstrahace
dehecho,calcularrutasmscortas.Laclaveesmostrarquecadavezqueseagregaunvrticeu
paraestablecerS,tenemosu:d.sDu/.

Teorema24.6(correccindelalgoritmodeDijkstra)
elalgoritmodeDijkstra,correrenunagrficaponderada,dirigidaGD.VE/nocon
funcindepesownegativoylafuentes,terminaconu:d.sDu/paratodos
vrticesu2V.

Pgina81

660 Captulo24cortasdeorigennicoCaminos

Usted
p2
S
S
p1 Y
x

Figura24.7Lademostracindelteorema24.6.ConjuntoSesnovacojustoantesdevrticeuseaadealamisma.Nosotros
p
x!y u,dondeyeslaprimera
descomponeruncaminomscortopdelafuentespasandoporelpuntoUens
p 1
2

vrticeenelcaminoquenoestenSyS2xprecedeinmediatamentey.Vrticesxeysondistintos,
peroesposiblequetengamossDDxoyu.LatrayectoriaP2puedeonovuelvenaentrarestablecerS.

PruebaUtilizamoselsiguienteinvariantesdebucle:
Alcomienzodecadaiteracindeltiempodebucledelaslneas48,:d.sD/
paracadavrtice2S.
Bastaconmencionarporcadavrticeu2V,tenemosu:d.sDu/enelmomentocuandou

https://translate.googleusercontent.com/translate_f 50/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
seaadealconjuntoS.Unavezquedemostramosqueu:d.sDu/,quesebasanenlacotasuperior
propiedadparademostrarquelaigualdadsecumpleentodomomentoapartirdeentonces.
Inicializacin:Inicialmente,DakotadelSuryaselinvarianteestrivialmentecierto.
Mantenimiento:Deseamosdemostrarqueencadaiteracin,u:DD.su/paraelvrtice
aadidoparaestablecerS.Paraelpropsitodelacontradiccin,Seauelprimervrticepara
queu:d.su/cuandoseaadealconjuntoS.nosvamosacentrarnuestraatencin
sobrelasituacinalcomienzodelaiteracindeltiempodebucleenelqueu
seaadeaSyderivarlacontradiccinqueu:d.sDu/enesemomentopor
elexamendeunarutamscortadesdeu.Debemostenerusporquesesel
primervrticeaadidoalconjuntoSys:d.sDs/D0enesemomento.Porqueus,
tambintenemosqueSjustoantesdeuseaadieronaS.Debehaberalguna
caminodesau,puesdelocontrariou:d.sDu/D1porlapropiedaddenocamino,
loqueviolaranuestrasuposicindequeu:d.su/.Debidoaquehayporlo
menosunatrayectoria,hayuncaminomscortopdesau.AntesdelaadicindeuparaS,
latrayectoriaPconectaunvrticeenS,esdecir,s,aunvrticedeVS,asaberu.Nosdeja
considerarelprimervrticeyalolargodeptalquey2VS,yseax2SserYes
predecesoralolargodep.Porlotanto,comolafigura24.7ilustra,podemosdescomponerlatrayectoriaP
p
ens x!y
1
p 2 U(Cualquieradeloscaminosp1op2puedentenerbordes.)
Reivindicamosquey:dD.scuandouseaadeaS.Parademostrarestaafirmacina/a,obstruccin
servirquex2S.Entonces,porqueelegimosucomoelprimervrticedelacual
u:d.su/,cuandoseaadeaS,tuvimosx:d.sDx/xcuandoseaadi

Pgina82

24.3algoritmodeDijkstra 661

aS.Edge.Xa/afuerelajadoenesemomento,ylareclamacinsedesprendedela
propiedaddeconvergencia.
Ahorapodemosobtenerunacontradiccinparaprobarqueu:d.sDu/.Debidoy
apareceantesdeuenuncaminomscortodesauytodoslospesosdelasaristassonno
negativo(enparticularlosdelatrayectoriaP2),tenemos.s.sa/au/,yporlotanto
y:dD.sa/
.sAu/ (24.2)
UnU:D (Porlapropiedaddellmitesuperior).
PerodebidoaqueambosvrticesueyestabanenV
Sucuandofueelegidoenlalnea5,
tenemosu:DAS:d.Porlotanto,lasdosdesigualdadesen(24.2)estnenigualdadesdehecho,
Dando

y:dD.s.sY/DT/TD:D:

Enconsecuencia,u:d.sDu/,locualcontradicenuestraeleccindeu.Concluimos
queu:d.sDu/ucuandoseaadeaS,yqueestaigualdadsemantienea
todomomentoapartirdeentonces.
Terminacin:Alaterminacin,unavezaldaque,juntoconnuestroinvarianteanteriormenteque
QDVS,implicaqueSDV.Porlotanto,u:d.sDu/uparatodoslosvrticesV2.

corolario24.7
SisecorreelalgoritmodeDijkstraenunagrficaponderada,dirigidaGD.VE/con
nonegativofuncinpesowylafuentes,acontinuacin,enlaterminacin,elpredecesor
subgrafoGesunrboldemscortacaminosconrazens.

Lapruebainmediatadelteorema24.6ylapropiedadpredecesorsubgrafo.

Anlisis
QutanrpidoeselalgoritmodeDijkstra?MantienelacoladeprioridadminQporllamada
ingtresoperacionesdeprioridadesdecola:Mensert(implcitaenlalnea3),EXTRACTMEN
(lnea5),yDECREASEKEY(implcitaenIELAX,quesellamaenlalnea8).El
algoritmollamatantoquensertyEXTRACTMENunavezalvrtice.Debidoaquecada
vrticeu2VseaadealconjuntoSexactamenteunavez,cadabordeenlalistadeadyacenciaAdjoeu
seexaminaeneldebucledelaslneas78exactamenteunavezduranteelcursodelaal
GorithmDadoqueelnmerototaldebordesentodaslaslistasdeadyacenciaesjej,estopara
bucleiterauntotaldevecesjej,yporlotantoelalgoritmollamaDECREASEKEYen
lamayoradelasvecesjejgenerales.(Tenerencuentaunavezmsqueestamosutilizandoanlisisagregado.)
EltiempodeejecucindelalgoritmodeDijkstradependedecmoseimplementala
mincoladeprioridad.Consideremosprimeroelcasoenquemantenemoslaprioridadmin

Pgina83

662 Captulo24cortasdeorigennicoCaminos

https://translate.googleusercontent.com/translate_f 51/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

colamedianteelaprovechamientodelosvrticesnumerados1ajVj.simplemente
almacn:denelTHdeentradadeunamatriz.CadaMensertyDECREASEKEYoperacin
tomaO.1/hora,ycadaEXTRACTMENoperacintomaOV/hora(yaque
tienequebuscaratravsdetodalamatriz),parauntiempototaldeVO2CE/DVO2/.
Sielgrficoessuficientementeescasaenparticular,EDoV2=LGV/Podemos
mejorarelalgoritmomediantelaaplicacindelacoladeprioridadminconunaminerabinaria
montn.(Comosediscutienlaseccin6.5,laaplicacindebeasegurarsedeque
vrticesyelementosmontncorrespondientesasasmantienenentres).Cada
EXTRACTMENoperacinacontinuacin,llevatiempoO.lgV/.Comoantes,hayjVjtales
Operaciones.EltiempoparaconstruirelbinariominmontnesOV/.CadaDECREASEKEY
operacinllevatiempoO.lgV/,ytodavahayenlamayoradejejestetipodeoperaciones.los
Porlotanto,eltiempototaldeejecucinesO..VCE/LGV/,queesOELGV/sitodoslosvrtices
sonaccesiblesdesdelafuente.Estetiempodefuncionamientomejoralastraightfor
saladeVO2/tiempoaplicacinsiEDoV2=LGV/.
dehecho,podemoslograruntiempodeejecucindeOVLGVCE/mediantelaaplicacindela
mincoladeprioridadconunmontndeFibonacci(vaseelCaptulo19).Elcostoamortizado
decadaunodelosjVjEXTRACTMENoperacionesesO.lgV/,ycadaDECREASE
KEYllamada,delasquehayenlamayorajej,tomasloO.1/horaamortizado.Su
histricamente,eldesarrollodeFibonaccimontonesfuemotivadaporlaobservacin
queelalgoritmodeDijkstranormalmentehacequemuchosmsDECREASEKEYllamade
EXTRACTMENllama,demodoquecualquiermtododereducireltiempodecadaamortizado
DECREASEKEYoperacinparao.lgV/sinaumentareltiempodeamortizacin
EXTRACTMENproduciraunaimplementacinasintticamentemsrpidoqueconbi
montonesrias.
elalgoritmodeDijkstraseparecetantoalabsquedaenamplitud(vaselaSeccin22.2)y
AlgoritmodePrimparaelclculoderbolesdeexpansinmnima(vaselaSeccin23.2).Es
comolabsquedaprimeroenamplitudeneseconjuntoScorrespondealconjuntodevrticesenunnegro
primeroenamplituddebsquedaaligualquelosvrticesenStienensuspesosfinalesdelarutamscorta,porlo
hacervrticesnegrosenunabsquedaenamplitudtienensusdistanciasenamplitudcorrectas.
elalgoritmodeDijkstraescomoelalgoritmodePrimenlaqueambosalgoritmosusanunaminera
coladeprioridadparaencontrarelvrtice"ligero"fueradeunconjuntodado(elconjuntoSdeDijkstra
algoritmoyelrbolquesecultivanenelalgoritmodePrim),sesumanestevrticeenel
estableceryajustarlospesosdelosvrticesrestantesfueradelconjuntoenconsecuencia.

Ceremonias
24,31
EjecutarelalgoritmodeDijkstraenelgrafodirigidodelafigura24.2,enprimerlugarutilizandovrtices
comolafuenteyluegousandovrtice'comolafuente.Enelestilodelafigura24.6,
mostrarlosvaloresyDylosvrticesenconjuntoSdespusdecadaiteracindeltiempo
lazo.

Pgina84

24.3algoritmodeDijkstra 663

24,32
Darunejemplosencillodeungrafodirigidoconbordesdepesonegativoparaloscuales
elalgoritmodeDijkstraproducerespuestasincorrectas.PorqunohacelapruebadeTheodor
rem24,6atraviesancuandosepermitequelosbordesdepesonegativo?

24,33
Supongamosquecambiamoslalnea4delalgoritmodeDijkstraalosiguiente.
4mientrasjQj>1

EstecambiohacequeeltiempodebucleparaejecutartiemposJVJ1enlugardeJVjveces.Es
estapropuestaalgoritmocorrecto?

24,34
ProfesorGaedelhaescritounprogramaqueimplementaafirmaaldeDijkstra
GorithmElprogramaproduce:dy:paracadavrtice 2V.daruna
OVCE/algoritmotiempoparacomprobarlasalidadelprogramadelprofesor.Debera
determinarsieldyatributoscoincidenconlosdealgnrbolmscortacaminos.
Ustedpuedeasumirquetodoslospesosdelasaristassonnonegativos.

24,35
ProfesorNewmancreequehatrabajadoacabounapruebasimpledelacorreccin
paraelalgoritmodeDijkstra.AfirmaqueelalgoritmodeDijkstrarelajalosbordesde
cadacaminomscortoenelgrficoenelordenenqueaparecenenelcamino,y
Porlotanto,lapropiedadpathrelajacinseaplicaatodoslosvrticesalcanzablesdesdeel
fuente.Demostrarqueelprofesorseconfundeconlaconstruccindeungrafodirigidopor
elalgoritmodeDijkstrapodrarelajarlosbordesdeuncaminomscortofueradeorden.

24,36
SenoshadadoungrafodirigidoGD.VE/enelquecadaborde.u/2Etieneuna
ruvalorasociado/,Queesunnmerorealenelintervalode0ru/A1que
https://translate.googleusercontent.com/translate_f 52/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
representalafiabilidaddeuncanaldecomunicacindesdeelvrticeualvrtice.
Interpretamosru/Comolaprobabilidaddequeelcanaldeuanofallar,
yasumimosqueestasprobabilidadessonindependientes.Darunalgoritmoeficiente
paraencontrarelcaminomsfiableentredosvrticesdados.

24,37
DejeGD.VE/ungrafoponderado,dirigidaconlafuncindepesopositivo
wWE!f12:::WgparaalgnenteropositivoW,yasumirquenohaydosver
ticastienenlosmismospesosrutamscortadesdeelvrticefuentes.Supongamosahoraque
definimosunponderado,grafodirigidoG0D.V[V0E0/reemplazandocada
.uborde/2Econwu/Unidaddepesobordesenserie.Cuntosvrtices
QuG0tiene?AhorasupongamosqueejecutaunabsquedaprimeroenamplitudenG0.Muestraesa

Pgina85

664 Captulo24cortasdeorigennicoCaminos

elordenenelquelabsquedaenamplituddeG0coloresvrticesenVeselnegro
mismoqueelordenenelqueelalgoritmodeDijkstraextraelosvrticesdeVdela
coladeprioridadcuandoseejecutaenG.

24,38
DejeGD.VE/ungrafoponderado,dirigidaconlafuncindepesononegativo
wWE!f01:::WgporalgnnmeroenterononegativoW.ModificaralgodeDijkstra
rithmparacalcularlasrutasmscortasdesdeunvrticefuentedadasenOWVCE/
hora.

24,39
ModificarelalgoritmodelEjercicio24,38parafuncionarenO..VCE/LBV/hora.
Sencualquier
(Pista:CuntosestimacionesdelarutamscortadistintospuedehaberenV
puntoeneltiempo?)

24,310
Supongamosquesenosdaunaponderada,grficodirigidoGD.VE/enelquelosbordes
quedejeelvrticefuentespuedentenerpesosnegativos,todoslosotrospesosdelasaristas
sonnonegativos,ynohayciclosdepesonegativo.ArgumentarqueDijkstra
algoritmoencuentracorrectamenterutasmscortasdesdesenestegrfico.

24.4limitacionesdediferenciayloscaminosmscortos

Captulo29estudiaelproblemadeprogramacinlinealgeneral,enlaquedeseamos
optimizarunafuncinlinealsujetaaunconjuntodedesigualdadeslineales.Enestaseccin,
investigaruncasoespecialdeprogramacinlinealquereducimosalabsquedademscorta
caminosdeunasolafuente.entoncespodemosresolverelorigennicodemscortacaminos
problemaquedalugaralejecutarelalgoritmodeBellmanFord,porlotantotambinlaresolucin
elproblemadeprogramacinlineal.

Programacinlineal
Engeneral,elproblemadeprogramacinlineal,senosdaunam nmatrizA,
unvectormb,yunnvectorc.Deseamosencontrarunvectorxdenelementosque
Pn
maximizalafuncinobjetivo ID1cixisujetoalasrestriccionesdadasporm
Hachaab.
Aunqueelalgoritmosimplex,queeselfocodelcaptulo29,nohace
siempreseejecutanentiempopolinomialeneltamaodesuentrada,hayotralinealidad
algoritmosdeprogramacinqueseejecutanentiempopolinmico.Ofrecemosaqudosrazones
paracomprenderlaconfiguracindeproblemasdeprogramacinlineal.Enprimerlugar,sisabemosquenos

Pgina86

24.4limitacionesdediferenciayloscaminosmscortos 665

puedeemitirundeterminadoproblemacomounproblemadeprogramacinlinealesunpolinomiodetamao,acontinuacin,
inmediatamentetenemosunalgoritmodetiempopolinmicopararesolverelproblema.Segundo,
Existenalgoritmosrpidosparamuchoscasosespecialesdeprogramacinlineal.Paraexamen
PLE,ladeunsoloparproblemadecaminomscorto(Ejercicio24,44)yelcaudalmximo
problema(Ejercicio26,15)soncasosespecialesdeprogramacinlineal.
AvecesnoleimportaenrealidadlafuncinobjetivoSlodeseamosencontrar
cualquiersolucinfactible,esdecir,cualquiervectorxquesatisfaceAxAB,oparadeterminar
quenoexisteningunasolucinviable.Noscentraremosenunodeesosproblemasdeviabilidad.

Sistemasdelimitacionesdediferencia
https://translate.googleusercontent.com/translate_f 53/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Enunsistemaderestriccionesdediferencia,cadafiladelamatrizdeprogramacinlinealA
contieneun1yun1,ytodoslosdemselementosdeAson0.Porlotanto,laslimitaciones
dadaporAxABsonunconjuntodemrestriccionesdediferenciaqueimplicanincgnitas,en
elquecadarestriccinesunsimpledesigualdadlinealdelaforma

xj xiABk

donde1aijan,ij,ky1m.
Porejemplo,consideremoselproblemadeencontrarun5vectorxD.xi/quesatisface
1 1 0 0 0 0
1 0 0 0 1 1
x1
0 1 0 0 1 1
x2
1 0 1 0 0 5
x3 UN :
1 0 0 1 0 4
x4
0 0 1 1 0 1
x5
0 0 1 0 1 3
0 0 0 1 1 3
Esteproblemaesequivalenteaencontrarvaloresdelasincgnitasx1x2x3x4x5,
quesatisfacelassiguienteslimitacionesdediferencia8:
x1 x2 UN 0, (24.3)
x1 x5 A1, (24,4)
x2 x5 UN 1, (24,5)
x3 x1 UN 5, (24.6)
x4 x1 UN 4, (24.7)
x4 x3 A1, (24,8)
x5 x3 A3, (24.9)
x5 x4 A3. (24.10)

Pgina87

666 Captulo24cortasdeorigennicoCaminos

UnasolucinaesteproblemaesxD0,53014/,quesepuedeverificardi
tamenteporelcontroldecadadesigualdad.Dehecho,esteproblematienemsdeunasolucin.
Otraesx0D0,02541/.Estasdossolucionessonrelacionados:cadacomponente
dex0es5mayorqueelcomponentecorrespondientedex.Estehechonoesunamera
coincidencia.

lema24.8
SeaxD.x1x2:::xn/serunasolucinaunsistemaAxABdelcondiferencia
restricciones,yseaDcualquierconstante.EntoncesxCDD.x1Cdx2Cd:::xnCd/
esunasolucindeAxABtambin.

PruebaParacadaxiyxj,tenemos.xjCd/.xiCd/Dxj xi.Porlotanto,six
satisfaceAxAB,tambinlohacexCd.

Sistemasdelimitacionesdediferenciaseproducenenmuchasaplicacionesdiferentes.porejem
amplias,lasincgnitasxipuedehaberocasionesenquelosacontecimientossevanaproducir.cadarestriccin
establecequealmenosunaciertacantidaddetiempo,oenmsdeunaciertacantidaddetiempo,
debetranscurrirentredoseventos.Talvezloseventossonpuestosdetrabajoquesedebenrealizardurante
ingelmontajedeunproducto.Siaplicamosunadhesivoquetarda2horasparaestableceren
tiempox1ytenemosqueesperarhastaqueseestableceparainstalarunaparteenelmomentox2,entoncestenemosla
restriccindequex2 x1C2o,equivalentemente,dequex
x2a2.Alternativamente,
1

puedenrequerirquelapartepuedeinstalardespusdequeeladhesivosehaaplicadoperono
mstardequeelmomentoenqueeladhesivosehafijadohastalamitad.Enestecaso,seobtieneelparde
limitacionesx2 x1yx2Ax1C1o,demaneraequivalente,x
x2a0yx
1 2 x1a1.

grficosderestriccin
Podemosinterpretarlossistemasdelaslimitacionesdediferenciadesdeunpuntogrficoterico
devista.EnunsistemaAxABdelaslimitacionesdediferencia,vemoselm norte
deprogramacinlinealmatrizAcomolatranspuestadeunamatrizdeincidencia(vercio
CISE22,17)paraungrafoconnvrticesyaristasm.Cadavrticeienelgrfico,
paraiD12:::n,correspondeaunodelosnvariablesdesconocidasxi.cadadi
rectedbordeenelgrficocorrespondeaunadelasmdesigualdadescondos
Desconocidos
Msformalmente,dadounsistemaAxABdelaslimitacionesdediferencia,lacorrespondiente
inggrficoderestriccinesungrafoponderado,dirigidaGD.VE/,donde
VDf01:::ng
y
EDf.ij/Wxj xiABkesunconstraintg

https://translate.googleusercontent.com/translate_f 54/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
[F.01/.02/.03/:::.0n/g:

Pgina88

24.4limitacionesdediferenciayloscaminosmscortos 667

0 v1
0 5
v5 1 0
4 1 3
0 v2
v0 0
3 3 5
4
0 1 1 0 v3
v4
0

Figura24.8Elgrficoderestriccincorrespondientealsistema(24.3)(24,10)decondiferencia
StraintsElvalordei.0i/apareceencadavrticei.Unasolucinviableparaelsistemaes
Dx0,53014/.

Elgrficoderestriccincontieneelvrticeadicional0,comoveremosenbreve,a
garantizarquelagrficatienealgnvrticequepuedellegaratodoslosotrosvrtices.As,
elconjuntodevrticesVconsisteenunvrticeiparacadaincgnitaxi,msunadicional
vrtice0.ElconjuntodearistasEcontieneunbordedecadarestriccindiferencia,incrementada
unborde.0i/paracadaincgnitaxi.Sixj xiABkesunarestriccindeladiferencia,
entonceselpesodeborde.ij/wes.ij/Dbk.Elpesodecadabordedejando
ing0es0.Figura24.8muestraelgrficoderestriccinparaelsistema(24.3)(24,10)
delaslimitacionesdediferencia.
Elsiguienteteoremamuestraquepodemosencontrarunasolucinaunsistemadediferencia
ENCElimitacionesmediantelabsquedadelospesosdelarutamscortaenlarestriccincorrespondiente
grafico.

teorema24.9
DadounsistemaAxABdelaslimitacionesdediferencia,ymuchoGD.VE/seaeldiente
pondientegrficoderestriccin.SiGnocontieneciclosdepesonegativo,entonces
xP.I.01/yo.02/yo.03/:::yo.0n// (24.11)
esunasolucinfactibleparaelsistema.SiGcontieneunciclodepesonegativo,entonces
nohayningunasolucinfactibleparaelsistema.

PruebaEnprimerlugar,demostramosquesielgrficoderestriccincontieneningnpesonegativo
ciclos,entonceslaecuacin(24.11)daunasolucinfactible.Considerelaposibilidaddecualquieradelosbordes
.ij/2E.Porladesigualdadtriangular,yo.0jI/a.0i/wC.ij/o,
equivalentemente,yo.0j/i.0i/Aw.ij/.Porlotanto,haciendoxidI.0i/y

Pgina89

668 Captulo24cortasdeorigennicoCaminos

xjdi.0j/satisfaceladiferenciarestriccinxj xiaw.ij/quecorres
pondeaborde.ij/.
Nowweshowthatiftheconstraintgraphcontainsanegativeweightcycle,then
thesystemofdifferenceconstraintshasnofeasiblesolution.Withoutlossofgen
erality,letthenegativeweightcyclebecDh12:::ki,where1Dk.
(Thevertex0cannotbeoncyclec,becauseithasnoenteringedges.)Cyclec
correspondstothefollowingdifferenceconstraints:
x2 x1 w.12/
x3 x2 w.23/
Unesdoc.unesco.orgunesdoc.unesco.org

xk1 xk2 w.k2k1/


xk xk1 w.k1k/:
Wewillassumethatxhasasolutionsatisfyingeachofthesekinequalitiesandthen
deriveacontradiction.Thesolutionmustalsosatisfytheinequalitythatresults
whenwesumthekinequalitiestogether.Ifwesumthelefthandsides,each
unknownxiisaddedinonceandsubtractedoutonce(rememberthat1Dk
impliesx1Dxk),sothatthelefthandsideofthesumis0.Therighthandside
sumstowc/,andthusweobtain0wc/.Butsincecisanegativeweightcycle,
wc/<0,andweobtainthecontradictionthat0wc/<0.
https://translate.googleusercontent.com/translate_f 55/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Solvingsystemsofdifferenceconstraints

Theorem24.9tellsusthatwecanusetheBellmanFordalgorithmtosolvea
systemofdifferenceconstraints.Becausetheconstraintgraphcontainsedges
fromthesourcevertex0toallothervertices,anynegativeweightcycleinthe
constraintgraphisreachablefrom0.IftheBellmanFordalgorithmreturns
TRUE,thentheshortestpathweightsgiveafeasiblesolutiontothesystem. En
Figure24.8,forexample,theshortestpathweightsprovidethefeasiblesolution
xD.53014/,andbyLemma24.8,xD.d5d3dd1d4/
isalsoafeasiblesolutionforanyconstantd.IftheBellmanFordalgorithmreturns
FALSE,thereisnofeasiblesolutiontothesystemofdifferenceconstraints.
Asystemofdifferenceconstraintswithmconstraintsonnunknownsproduces
agraphwithnC1verticesandnCmedges.Thus,usingtheBellmanFord
algorithm,wecansolvethesysteminO..nC1/.nCm//DOn2Cnm/time.
Exercise24.45asksyoutomodifythealgorithmtoruninO.nm/time,evenifm
ismuchlessthann.

Pgina90

24.4Differenceconstraintsandshortestpaths 669

Exercises
24.41
Findafeasiblesolutionordeterminethatnofeasiblesolutionexistsforthefollow
ingsystemofdifferenceconstraints:
x1 x2 UN 1,
x1 x4 4,
x2 x3 UN 2,
x2 x5 UN 7,
x2 x6 UN 5,
x3 x6 10,
x4 x2 UN 2,
x5 x1 1,
x5 x4 UN 3,
x6 x3 8.

24.42
Findafeasiblesolutionordeterminethatnofeasiblesolutionexistsforthefollow
ingsystemofdifferenceconstraints:
x1 x2 UN 4,
x1 x5 UN 5,
x2 x4 6,
x3 x2 UN 1,
x4 x1 UN 3,
x4 x3 UN 5,
x4 x5 10,
x5 x3 4,
x5 x4 8.

24.43
Cananyshortestpathweightfromthenewvertex0inaconstraintgraphbeposi
tive?Explique.

24.44
Expressthesinglepairshortestpathproblemasalinearprogram.

Pgina91

670 Chapter24SingleSourceShortestPaths

24.45
ShowhowtomodifytheBellmanFordalgorithmslightlysothatwhenweuseit
https://translate.googleusercontent.com/translate_f 56/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
tosolveasystemofdifferenceconstraintswithminequalitiesonnunknowns,the
runningtimeisO.nm/.

24.46
Supposethatinadditiontoasystemofdifferenceconstraints,wewanttohandle
equalityconstraintsoftheformxiDxjCbk.ShowhowtoadapttheBellman
Fordalgorithmtosolvethisvarietyofconstraintsystem.

24.47
ShowhowtosolveasystemofdifferenceconstraintsbyaBellmanFordlikealgo
rithmthatrunsonaconstraintgraphwithouttheextravertex0.

24.48?
LetAxbbeasystemofmdifferenceconstraintsinnunknowns.Showthatthe
BellmanFordalgorithm,whenrunonthecorrespondingconstraintgraph,maxi
Pn
mizes iD1xisubjecttoAxbandxi0forallxi.

24.49?
ShowthattheBellmanFordalgorithm,whenrunontheconstraintgraphforasys
temAxbofdifferenceconstraints,minimizesthequantity.maxfxigminfxig/
subjecttoAxb.Explainhowthisfactmightcomeinhandyifthealgorithmis
usedtoscheduleconstructionjobs.

24.410
SupposethateveryrowinthematrixAofalinearprogramAxbcorrespondsto
adifferenceconstraint,asinglevariableconstraintoftheformxibk,orasingle
variableconstraintoftheformxibk.ShowhowtoadapttheBellmanFord
algorithmtosolvethisvarietyofconstraintsystem.

24.411
GiveanefficientalgorithmtosolveasystemAxbofdifferenceconstraints
whenalloftheelementsofbarerealvaluedandalloftheunknownsximustbe
integers.

24.412?
GiveanefficientalgorithmtosolveasystemAxbofdifferenceconstraints
whenalloftheelementsofbarerealvaluedandaspecifiedsubsetofsome,but
notnecessarilyall,oftheunknownsximustbeintegers.

Page92

24.5Proofsofshortestpathsproperties 671

24.5Proofsofshortestpathsproperties

Throughoutthischapter,ourcorrectnessargumentshavereliedonthetriangle
inequality,upperboundproperty,nopathproperty,convergenceproperty,path
relaxationproperty,andpredecessorsubgraphproperty.Westatedtheseproperties
withoutproofatthebeginningofthischapter.Inthissection,weprovethem.

Thetriangleinequality
Instudyingbreadthfirstsearch(Section22.2),weprovedasLemma22.1asim
plepropertyofshortestdistancesinunweightedgraphs.Thetriangleinequality
generalizesthepropertytoweightedgraphs.

Lemma24.10(Triangleinequality)
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R
andsourcevertexs.Then,foralledges.u/2E,wehave
.s/.su/Cwu/:

ProofSupposethatpisashortestpathfromsourcestovertex.Thenphas
nomoreweightthananyotherpathfromsto.Specifically,pathphasnomore
weightthantheparticularpaththattakesashortestpathfromsourcestovertexu
andthentakesedge.u/.
Exercise24.53asksyoutohandlethecaseinwhichthereisnoshortestpath
fromsto.

Effectsofrelaxationonshortestpathestimates
Thenextgroupoflemmasdescribeshowshortestpathestimatesareaffectedwhen
weexecuteasequenceofrelaxationstepsontheedgesofaweighted,directed
graphthathasbeeninitializedbyINITIALIZESINGLESOURCE.

https://translate.googleusercontent.com/translate_f 57/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Lemma24.11(Upperboundproperty)
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R.
Lets2Vbethesourcevertex,andletthegraphbeinitializedbyINITIALIZE
SINGLESOURCE.Gs/.Then,:d .s/forall2V,andthisinvariantis
maintainedoveranysequenceofrelaxationstepsontheedgesofG.Moreover,
once:dachievesitslowerbound.s/,itneverchanges.

Pgina93

672 Chapter24SingleSourceShortestPaths

ProofWeprovetheinvariant:d .s/forallvertices2Vbyinduction
overthenumberofrelaxationsteps.
Forthebasis,:d .s/iscertainlytrueafterinitialization,since:dD1
implies:d .s/forall2V fsg,andsinces:dD0 .ss/(notethat
.ss/D1ifsisonanegativeweightcycleand0otherwise).
Fortheinductivestep,considertherelaxationofanedge.u/.Bytheinductive
hypothesis,x:d .sx/forallx2Vpriortotherelaxation.Theonlydvalue
thatmaychangeis:d.Ifitchanges,wehave
:dDu:dCwu/
.su/Cwu/(bytheinductivehypothesis)
.s/ (bythetriangleinequality),
andsotheinvariantismaintained.
Toseethatthevalueof:dneverchangesonce:dD.s/,notethathaving
achieveditslowerbound,:dcannotdecreasebecausewehavejustshownthat
:d .s/,anditcannotincreasebecauserelaxationstepsdonotincreased
valores.

Corollary24.12(Nopathproperty)
Supposethatinaweighted,directedgraphGD.VE/withweightfunction
wWE!R,nopathconnectsasourcevertexs2Vtoagivenvertex 2V.
Then,afterthegraphisinitializedbyINITIALIZESINGLESOURCE.Gs/,we
have:dD.s/D1,andthisequalityismaintainedasaninvariantover
anysequenceofrelaxationstepsontheedgesofG.

ProofBytheupperboundproperty,wealwayshave1D.s/:d,and
thus:dD1D.s/.

Lemma24.13
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R,
andlet.u/2E.Then,immediatelyafterrelaxingedge.u/byexecuting
RELAX.uw/,wehave:du:dCwu/.

ProofIf,justpriortorelaxingedge.u/,wehave:d>u:dCwu/,then
:dDu:dCwu/afterward.If,instead,:du:dCwu/justbefore
therelaxation,thenneitheru:dnor:dchanges,andso:du:dCwu/
afterward.

Lemma24.14(Convergenceproperty)
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R,
lets2Vbeasourcevertex,andletsu! beashortestpathinGfor

Pgina94

24.5Proofsofshortestpathsproperties 673

someverticesu2V.SupposethatGisinitializedbyINITIALIZESINGLE
SOURCE.Gs/andthenasequenceofrelaxationstepsthatincludesthecall
RELAX.uw/isexecutedontheedgesofG.Ifu:dD.su/atanytime
priortothecall,then:dD.s/atalltimesafterthecall.

ProofBytheupperboundproperty,ifu:dD.su/atsomepointpriortore
laxingedge.u/,thenthisequalityholdsthereafter.Inparticular,afterrelaxing
edge.u/,wehave
:du:dCwu/ (byLemma24.13)
D.su/Cwu/
D.s/ (byLemma24.1).

https://translate.googleusercontent.com/translate_f 58/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Bytheupperboundproperty,:d .s/,fromwhichweconcludethat
:dD.s/,andthisequalityismaintainedthereafter.

Lemma24.15(Pathrelaxationproperty)
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R,
andlets2Vbeasourcevertex.ConsideranyshortestpathpDh01:::ki
fromsD0tok.IfGisinitializedbyINITIALIZESINGLESOURCE.Gs/and
thenasequenceofrelaxationstepsoccursthatincludes,inorder,relaxingtheedges
.01/.12/:::.k1k/,thenk:dD.sk/aftertheserelaxationsand
atalltimesafterward.Thispropertyholdsnomatterwhatotheredgerelaxations
occur,includingrelaxationsthatareintermixedwithrelaxationsoftheedgesofp.

ProofWeshowbyinductionthataftertheithedgeofpathpisrelaxed,wehave
i:dD.si/.Forthebasis,iD0,andbeforeanyedgesofphavebeenrelaxed,
wehavefromtheinitializationthat0:dDs:dD0D.ss/.Bytheupperbound
property,thevalueofs:dneverchangesafterinitialization.
Fortheinductivestep,weassumethati1:dD.si1/,andweexamine
whathappenswhenwerelaxedge.i1i/.Bytheconvergenceproperty,after
relaxingthisedge,wehavei:dD.si/,andthisequalityismaintainedatall
timesthereafter.

Relaxationandshortestpathstrees
Wenowshowthatonceasequenceofrelaxationshascausedtheshortestpathes
timatestoconvergetoshortestpathweights,thepredecessorsubgraphGinduced
bytheresulting valuesisashortestpathstreeforG.Westartwiththefollow
inglemma,whichshowsthatthepredecessorsubgraphalwaysformsarootedtree
whoserootisthesource.

Pgina95

674 Chapter24SingleSourceShortestPaths

Lemma24.16
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R,
lets2Vbeasourcevertex,andassumethatGcontainsnonegativeweight
cyclesthatarereachablefroms.Then,afterthegraphisinitializedbyINITIALIZE
SINGLESOURCE.Gs/,thepredecessorsubgraphGformsarootedtreewith
roots,andanysequenceofrelaxationstepsonedgesofGmaintainsthisproperty
asaninvariant.

ProofInitially,theonlyvertexinGisthesourcevertex,andthelemmaistriv
iallytrue.ConsiderapredecessorsubgraphGthatarisesafterasequenceof
relaxationsteps.WeshallfirstprovethatGisacyclic.Supposeforthesakeof
contradictionthatsomerelaxationstepcreatesacycleinthegraphG.Letthecy
clebecDh01:::ki,wherekD0.Then,i:Di1foriD12:::K
and,withoutlossofgenerality,wecanassumethatrelaxingedge.k1k/created
thecycleinG.
Weclaimthatallverticesoncyclecarereachablefromthesources.Porqu?
EachvertexonchasanonNILpredecessor,andsoeachvertexoncwasassigned
afiniteshortestpathestimatewhenitwasassigneditsnonNIL valor.Porel
upperboundproperty,eachvertexoncyclechasafiniteshortestpathweight,
whichimpliesthatitisreachablefroms.
Weshallexaminetheshortestpathestimatesoncjustpriortothecall
RELAX.k1kw/andshowthatcisanegativeweightcycle,therebycontra
dictingtheassumptionthatGcontainsnonegativeweightcyclesthatarereachable
fromthesource.Justbeforethecall,wehavei:Di1foriD12:::k1.
Thus,foriD12:::K 1,thelastupdatetoi:dwasbytheassignment
i:dDi1:dCw. i1i/.Ifi1:dchangedsincethen,itdecreased. Porlotanto,
justbeforethecallRELAX.k1kw/,wehave

i:d i1:dCw. i1i/ foralliD12:::k1: (24.12)


Becausek:ischangedbythecall,immediatelybeforehandwealsohavethe
strictinequality

k:d>k1:dCw. k1k/:
Summingthisstrictinequalitywiththek 1inequalities(24.12),weobtainthe
sumoftheshortestpathestimatesaroundcyclec:
xK xK
i:d> .i1:dCw.i1i//
ID1 ID1
xK xK
re i1:dC w.i1i/:
ID1 ID1

https://translate.googleusercontent.com/translate_f 59/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina96

24.5Proofsofshortestpathsproperties 675

x
Z
S V
Usted
Y

Figure24.9ShowingthatasimplepathinGfromsourcestovertexisunique.Iftherearetwo
pathsp1(sux!)andp2(suy!),wherexy,then:Dx
and:Dy,acontradiction.

Pero
xK xK
i:dD i1:d
ID1 ID1
sinceeachvertexinthecyclecappearsexactlyonceineachsummation.Esta
equalityimplies
xK
0> w.i1i/:
ID1
Thus,thesumofweightsaroundthecyclecisnegative,whichprovidesthedesired
contradiction.
WehavenowproventhatGisadirected,acyclicgraph.Toshowthatitforms
arootedtreewithroots,itsuffices(seeExerciseB.52)toprovethatforeach
vertex2V,thereisauniquesimplepathfromstoinG.
WefirstmustshowthatapathfromsexistsforeachvertexinV.Thever
ticesinVarethosewithnonNIL values,pluss.Theideahereistoproveby
inductionthatapathexistsfromstoallverticesinV.Weleavethedetailsas
Exercise24.56.
Tocompletetheproofofthelemma,wemustnowshowthatforanyvertex
2V,thegraphGcontainsatmostonesimplepathfromsto.Supposeother
sabio.Thatis,supposethat,asFigure24.9illustrates,Gcontainstwosimplepaths
fromstosomevertex:p1,whichwedecomposeintosUx!,
andp2,whichwedecomposeintosUy!,wherexy(thoughu
couldbesandcouldbe).Butthen,:Dxand:Dy,whichimplies
thecontradictionthatxDy.WeconcludethatGcontainsauniquesimplepath
fromsto,andthusGformsarootedtreewithroots.

Wecannowshowthatif,afterwehaveperformedasequenceofrelaxationsteps,
allverticeshavebeenassignedtheirtrueshortestpathweights,thenthepredeces
sorsubgraphGisashortestpathstree.

Page97

676 Chapter24SingleSourceShortestPaths

Lemma24.17(Predecessorsubgraphproperty)
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R,
lets2Vbeasourcevertex,andassumethatGcontainsnonegativeweightcycles
thatarereachablefroms.LetuscallINITIALIZESINGLESOURCE.Gs/andthen
executeanysequenceofrelaxationstepsonedgesofGthatproduces:dD.s/
forall2V.Then,thepredecessorsubgraphGisashortestpathstreerooted
ats.

ProofWemustprovethatthethreepropertiesofshortestpathstreesgivenon
page647holdforG.Toshowthefirstproperty,wemustshowthatVistheset
ofverticesreachablefroms.Bydefinition,ashortestpathweight.s/isfinite
ifandonlyifisreachablefroms,andthustheverticesthatarereachablefroms
areexactlythosewithfinitedvalues.Butavertex2V fsghasbeenassigned
afinitevaluefor:difandonlyif:NIL.Thus,theverticesinVareexactly
thosereachablefroms.
ThesecondpropertyfollowsdirectlyfromLemma24.16.
Itremains,therefore,toprovethelastpropertyofshortestpathstrees:foreach
vertex2V,theuniquesimplepaths pag
inGisashortestpathfromsto
inG.LetpDh01:::ki,where0DsandkD.ForiD12:::k,
wehavebothi:dD.si/andi:d i1:dCw. i1i/,fromwhichwe
concludew.i1i/.si/.si1/.Summingtheweightsalongpathp
Rendimientos
xK
wp/D w.i1i/

https://translate.googleusercontent.com/translate_f 60/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
ID1
xK
UN ..si/.si1//
ID1
D.sk/.s0/ (becausethesumtelescopes)
D.sk/ (because.s0/D.ss/D0).

Thus,wp/.sk/.Since.sk/isalowerboundontheweightofanypath
fromstok,weconcludethatwp/D.sk/,andthuspisashortestpath
fromstoDk.

Exercises

24.51
GivetwoshortestpathstreesforthedirectedgraphofFigure24.2(onpage648)
otherthanthetwoshown.

Pgina98

24.5Proofsofshortestpathsproperties 677

24.52
Giveanexampleofaweighted,directedgraphGD.VE/withweightfunction
wWE!RandsourcevertexssuchthatGsatisfiesthefollowingproperty:For
everyedge.u/2E,thereisashortestpathstreerootedatsthatcontains.u/
andanothershortestpathstreerootedatsthatdoesnotcontain.u/.

24.53
EmbellishtheproofofLemma24.10tohandlecasesinwhichshortestpath
weightsare1or1.

24.54
LetGD.VE/beaweighted,directedgraphwithsourcevertexs,andletG
beinitializedbyINITIALIZESINGLESOURCE.Gs/.Provethatifasequenceof
relaxationstepssetss:toanonNILvalue,thenGcontainsanegativeweight
ciclo.

24.55
LetGD.VE/beaweighted,directedgraphwithnonegativeweightedges.Dejar
s2Vbethesourcevertex,andsupposethatweallow:tobethepredecessor
ofonanyshortestpathtofromsourcesif2V fsgisreachablefroms,
andNILotherwise.GiveanexampleofsuchagraphGandanassignmentof
valuesthatproducesacycleinG.(ByLemma24.16,suchanassignmentcannot
beproducedbyasequenceofrelaxationsteps.)

24.56
LetGD.VE/beaweighted,directedgraphwithweightfunctionwWE!R
andnonegativeweightcycles.Lets2Vbethesourcevertex,andletGbeinitial
izedbyINITIALIZESINGLESOURCE.Gs/.Provethatforeveryvertex2V,
thereexistsapathfromstoinGandthatthispropertyismaintainedasan
invariantoveranysequenceofrelaxations.

24.57
LetGD.VE/beaweighted,directedgraphthatcontainsnonegativeweight
CiclosLets2Vbethesourcevertex,andletGbeinitializedbyINITIALIZE
SINGLESOURCE.Gs/.ProvethatthereexistsasequenceofjVj1relaxation
stepsthatproduces:dD.s/forall2V.

24.58
LetGbeanarbitraryweighted,directedgraphwithanegativeweightcyclereach
ablefromthesourcevertexs.Showhowtoconstructaninfinitesequenceofrelax
ationsoftheedgesofGsuchthateveryrelaxationcausesashortestpathestimate
tochange.

Pgina99

678 Chapter24SingleSourceShortestPaths

Problemas

241Yen'simprovementtoBellmanFord
SupposethatweordertheedgerelaxationsineachpassoftheBellmanFordal
https://translate.googleusercontent.com/translate_f 61/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
gorithmasfollows.Beforethefirstpass,weassignanarbitrarylinearorder
12:::jVjtotheverticesoftheinputgraphGD.VE/.Then,weparti
tiontheedgesetEintoEf[Eb,whereEfDf.ij/2EWi<jgand
EbDf.ij/2EWi>jg.(AssumethatGcontainsnoselfloops,sothatevery
edgeisineitherEforEb.)DefineGfD.VEf/andGbD.VEb/.

a.ProvethatGfisacyclicwithtopologicalsorth12:::jVjiandthatGbis
acyclicwithtopologicalsorthjVjjVj1:::1i.

SupposethatweimplementeachpassoftheBellmanFordalgorithminthefol
lowingway.Wevisiteachvertexintheorder12:::jVj,relaxingedgesofEf
thatleavethevertex.WethenvisiteachvertexintheorderjVjjVj1:::1,
relaxingedgesofEbthatleavethevertex.

segundo.Provethatwiththisscheme,ifGcontainsnonegativeweightcyclesthatare
reachablefromthesourcevertexs,thenafteronlydjVj=2epassesoverthe
edges,:dD.s/forallvertices2V.

do.DoesthisschemeimprovetheasymptoticrunningtimeoftheBellmanFord
algorithm?

242Nestingboxes
Addimensionalboxwithdimensions.x1x2:::xd/nestswithinanotherbox
withdimensions.y1y2:::yd/ifthereexistsapermutation onf12:::Dg
suchthatx.1/<y1,x.2/<y2,...,x.d/<yd.

a.Arguethatthenestingrelationistransitive.

segundo.Describeanefficientmethodtodeterminewhetherornotoneddimensional
boxnestsinsideanother.

do.SupposethatyouaregivenasetofnddimensionalboxesfB1B2:::Bng.
GiveanefficientalgorithmtofindthelongestsequencehBi Bi :::Bi iof
1 2 k

boxessuchthatBi nestswithinBi
j forjD12:::K
jC1 1.Expressthe
runningtimeofyouralgorithmintermsofnandd.

Pgina100

ProblemsforChapter24 679

243Arbitrage
Arbitrageistheuseofdiscrepanciesincurrencyexchangeratestotransformone
unitofacurrencyintomorethanoneunitofthesamecurrency.Porejemplo,
supposethat1USdollarbuys49Indianrupees,1Indianrupeebuys2Japanese
yen,and1Japaneseyenbuys0:0107USdollars.Then,byconvertingcurrencies,
atradercanstartwith1USdollarandbuy4920:0107D1:0486USdollars,
thusturningaprofitof4:86percent.
Supposethatwearegivenncurrenciesc1c2:::cnandannntableRof
exchangerates,suchthatoneunitofcurrencycibuysRijunitsofcurrencycj.
a.Giveanefficientalgorithmtodeterminewhetherornotthereexistsasequence
ofcurrencieshci ci :::ci isuchthat
1 2 k

Ri1i2Ri2i3Rik1ikRiki1>1:

Analyzetherunningtimeofyouralgorithm.

segundo.Giveanefficientalgorithmtoprintoutsuchasequenceifoneexists.Analizar
therunningtimeofyouralgorithm.

244Gabow'sscalingalgorithmforsinglesourceshortestpaths
Ascalingalgorithmsolvesaproblembyinitiallyconsideringonlythehighest
orderbitofeachrelevantinputvalue(suchasanedgeweight).Itthenrefinesthe
initialsolutionbylookingatthetwohighestorderbits.Itprogressivelylooksat
moreandmorehighorderbits,refiningthesolutioneachtime,untilithasexam
inedallbitsandcomputedthecorrectsolution.
Inthisproblem,weexamineanalgorithmforcomputingtheshortestpathsfrom
asinglesourcebyscalingedgeweights.WearegivenadirectedgraphGD.VE/
withnonnegativeintegeredgeweightsw.LetWDmax.u/2Efw.u/g.Nuestra
goalistodevelopanalgorithmthatrunsinOElgW/time.Weassumethatall
verticesarereachablefromthesource.
Thealgorithmuncoversthebitsinthebinaryrepresentationoftheedgeweights
oneatatime,fromthemostsignificantbittotheleastsignificantbit.Especficamente,
letkDdlg.WC1/ebethenumberofbitsinthebinaryrepresentationofW,
andforiD12:::k,letwi.u/Dwu/=2ki .Thatis,wi.u/isthe
scaleddownversionofwu/givenbytheimostsignificantbitsofwu/.
(Thus,wk.u/Dwu/forall.u/2E.)Forexample,ifkD5and
https://translate.googleusercontent.com/translate_f 62/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
wu/D25,whichhasthebinaryrepresentationh11001i,thenw3.uD
h110iD6.AsanotherexamplewithkD5,ifwu/Dh00100iD4,then
w3.u/Dh001iD1.Letusdefinei.u/astheshortestpathweightfrom
vertexutovertexusingweightfunctionwi.Thus,k.u/D.u/forall
u2V.Foragivensourcevertexs,thescalingalgorithmfirstcomputesthe

Pgina101

680 Chapter24SingleSourceShortestPaths

shortestpathweights1.s/forall2V,thencomputes2.s/forall2V,
andsoon,untilitcomputesk.s/forall 2V.Weassumethroughoutthat
jEjjVj1,andweshallseethatcomputingifromi1takesOE/time,so
thattheentirealgorithmtakesO.kE/DOElgW/time.

a.Supposethatforallvertices2V,wehave.s/jEj.Showthatwecan
compute.s/forall2VinOE/time.

segundo.Showthatwecancompute1.s/forall2VinOE/time.

Letusnowfocusoncomputingifromi1.

do.ProvethatforiD23:::k,wehaveeitherwi.u/D2wi1.u/or
wi.u/D2wi1.u/C1.Then,provethat

2i1.s/i.s/2i1.s/CjVj1

forall2V.

re.DefineforiD23:::kandall.u/2E,

ywi.u/Dwi.u/C2i1.su/2i1.s/:

ProvethatforiD23:::kandallu2V,thereweightedvalueywi.u/
ofedge.u/isanonnegativeinteger.

mi.Now,define Yi.s/astheshortestpathweightfromstousingtheweight
functionywi.ProvethatforiD23:::kandall2V,

i.s/Dyi.s/C2i1.s/

yeso Y
i.s/jEj.

f.Showhowtocomputei.s/fromi1.s/forall2VinOE/time,and
concludethatwecancompute.s/forall2VinOElgW/time.

245Karp'sminimummeanweightcyclealgorithm
LetGD.VE/beadirectedgraphwithweightfunctionwWE!R,andlet
nDjVj.WedefinethemeanweightofacyclecDhe1e2:::ekiofedgesinE
ser

1 xK
.c/D wei/:
K
ID1

Pgina102

ProblemsforChapter24 681

Dejar Dminc .c/,wherecrangesoveralldirectedcyclesinG.Wecallacyclec


forwhich.c/D aminimummeanweightcycle.Thisprobleminvestigates
anefficientalgorithmforcomputing .
Assumewithoutlossofgeneralitythateveryvertex2Visreachablefroma
sourcevertexs2V.Let.s/betheweightofashortestpathfromsto,andlet
k.s/betheweightofashortestpathfromstoconsistingofexactlykedges.
Ifthereisnopathfromstowithexactlykedges,thenk.s/D1.
a.Showthatif D0,thenGcontainsnonegativeweightcyclesand.s/D
min0kn1k.s/forallvertices2V.

segundo.Showthatif
D0,then
n.s/k.s/
Mximo 0
0kn1 nk
forallvertices2V.(Hint:Usebothpropertiesfrompart(a).)

https://translate.googleusercontent.com/translate_f 63/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
do.Letcbea0weightcycle,andletuandbeanytwoverticesonc.Suponer
ese D0andthattheweightofthesimplepathfromutoalongthecycle
isx.Provethat.s/D.su/Cx.(Hint:Theweightofthesimplepath
fromtoualongthecycleisx.)

re.Showthatif D0,thenoneachminimummeanweightcyclethereexistsa
vertexsuchthat
n.s/k.s/
Mximo D0:
0kn1 nk
(Hint:Showhowtoextendashortestpathtoanyvertexonaminimummean
weightcyclealongthecycletomakeashortestpathtothenextvertexonthe
cycle.)

mi.Showthatif D0,then
n.s/k.s/
min Mximo D0:
2V 0kn1 nk
f.ShowthatifweaddaconstantttotheweightofeachedgeofG,then
increasesbyt.Usethisfacttoshowthat
n.s/k.s/
Dmin Mximo :
2V 0kn1 nk
g.GiveanO.VE/timealgorithmtocompute .

Pgina103

682 Chapter24SingleSourceShortestPaths

246Bitonicshortestpaths
Asequenceisbitonicifitmonotonicallyincreasesandthenmonotonicallyde
creases,orifbyacircularshiftitmonotonicallyincreasesandthenmonotonically
DisminuyeForexamplethesequencesh146832i,h924105i,and
h1234iarebitonic,buth13124210iisnotbitonic.(SeeProblem153for
thebitoniceuclideantravelingsalesmanproblem.)
SupposethatwearegivenadirectedgraphGD.VE/withweightfunction
wWE!R,wherealledgeweightsareunique,andwewishtofindsinglesource
shortestpathsfromasourcevertexs.Wearegivenoneadditionalpieceofinfor
mation:foreachvertex2V,theweightsoftheedgesalonganyshortestpath
fromstoformabitonicsequence.
Givethemostefficientalgorithmyoucantosolvethisproblem,andanalyzeits
runningtime.

Chapternotes

Dijkstra'salgorithm[88]appearedin1959,butitcontainednomentionofapriority
cola.TheBellmanFordalgorithmisbasedonseparatealgorithmsbyBellman
[38]andFord[109].Bellmandescribestherelationofshortestpathstodifference
Restricciones.Lawler[224]describesthelineartimealgorithmforshortestpathsin
adag,whichheconsiderspartofthefolklore.
Whenedgeweightsarerelativelysmallnonnegativeintegers,wehavemoreef
ficientalgorithmstosolvethesinglesourceshortestpathsproblem.Lasecuencia
ofvaluesreturnedbytheEXTRACTMINcallsinDijkstra'salgorithmmonoton
icallyincreasesovertime.AsdiscussedinthechapternotesforChapter6,in
thiscaseseveraldatastructurescanimplementthevariouspriorityqueueopera
tionsmoreefficientlythanabinaryheaporaFibonacciheap.Ahuja,Mehlhorn,
pag
Orlin,andTarjan[8]giveanalgorithmthatrunsinOECV lgW/timeon
graphswithnonnegativeedgeweights,whereWisthelargestweightofanyedge
inthegraph.ThebestboundsarebyThorup[337],whogivesanalgorithmthat
runsinOElglgV/time,andbyRaman[291],whogivesanalgorithmthatruns

inOECVmin .lgV/1=3C.lgW/1=4C hora.Thesetwoalgorithmsusean
amountofspacethatdependsonthewordsizeoftheunderlyingmachine.Alabama
thoughtheamountofspaceusedcanbeunboundedinthesizeoftheinput,itcan
bereducedtobelinearinthesizeoftheinputusingrandomizedhashing.
Forundirectedgraphswithintegerweights,Thorup[336]givesanOVCE/
timealgorithmforsinglesourceshortestpaths.Incontrasttothealgorithmsmen
tionedinthepreviousparagraph,thisalgorithmisnotanimplementationofDijk

Pgina104

https://translate.googleusercontent.com/translate_f 64/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
NotesforChapter24 683

stra'salgorithm,sincethesequenceofvaluesreturnedbyEXTRACTMINcalls
doesnotmonotonicallyincreaseovertime.
Forgraphswithnegativeedgeweights,analgorithmduetoGabowandTar
pag
jan[122]runsinO.
pag VElg.VW//time,andonebyGoldberg[137]runsin
O. VElgW/time,whereWDmax.u/2Efjw.u/jg.
Cherkassky,Goldberg,andRadzik[64]conductedextensiveexperimentscom
paringvariousshortestpathalgorithms.

Pgina105

25 AllPairsShortestPaths

Inthischapter,weconsidertheproblemoffindingshortestpathsbetweenallpairs
ofverticesinagraph.Thisproblemmightariseinmakingatableofdistancesbe
tweenallpairsofcitiesforaroadatlas.AsinChapter24,wearegivenaweighted,
directedgraphGD.VE/withaweightfunctionwWE!Rthatmapsedges
torealvaluedweights.Wewishtofind,foreverypairofverticesu2V,a
shortest(leastweight)pathfromuto,wheretheweightofapathisthesumof
theweightsofitsconstituentedges.Wetypicallywanttheoutputintabularform:
theentryinu'srowand'scolumnshouldbetheweightofashortestpathfromu
to.
Wecansolveanallpairsshortestpathsproblembyrunningasinglesource
shortestpathsalgorithmjVjtimes,onceforeachvertexasthesource.Mecaigo
edgeweightsarenonnegative,wecanuseDijkstra'salgorithm.Ifweuse
thelineararrayimplementationoftheminpriorityqueue,therunningtimeis
OV3CVE/DOV3/.Thebinaryminheapimplementationoftheminpriority
queueyieldsarunningtimeofO.VElgV/,whichisanimprovementifthegraph
issparse.Alternatively,wecanimplementtheminpriorityqueuewithaFibonacci

https://translate.googleusercontent.com/translate_f 65/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
heap,yieldingarunningtimeofOV 2lgVCVE/.
Ifthegraphhasnegativeweightedges,wecannotuseDijkstra'salgorithm.En
stead,wemustruntheslowerBellmanFordalgorithmoncefromeachvertex.los
resultingrunningtimeisOV2E/,whichonadensegraphisOV4/.Inthischap
terweshallseehowtodobetter.Wealsoinvestigatetherelationoftheallpairs
shortestpathsproblemtomatrixmultiplicationandstudyitsalgebraicstructure.
Unlikethesinglesourcealgorithms,whichassumeanadjacencylistrepresen
tationofthegraph,mostofthealgorithmsinthischapteruseanadjacency
matrixrepresentation.(Johnson'salgorithmforsparsegraphs,inSection25.3,
usesadjacencylists.)Forconvenience,weassumethattheverticesarenumbered
12:::jVj,sothattheinputisannnmatrixWrepresentingtheedgeweights
ofannvertexdirectedgraphGD.VE/.Thatis,WD.wij/,where

Pgina106

Chapter25AllPairsShortestPaths 685
Un

0 ifiDj
wijD theweightofdirectededge.ij/ifijand.ij/2E (25.1)
1 ifijand.ij/62E:
Weallownegativeweightedges,butweassumeforthetimebeingthattheinput
graphcontainsnonegativeweightcycles.
Thetabularoutputoftheallpairsshortestpathsalgorithmspresentedinthis
chapterisannnmatrixDD.dij/,whereentrydijcontainstheweightofa
shortestpathfromvertexitovertexj.Thatis,ifwelet.ij/denotetheshortest
pathweightfromvertexitovertexj(asinChapter24),thendijD.ij/at
termination.
Tosolvetheallpairsshortestpathsproblemonaninputadjacencymatrix,we
needtocomputenotonlytheshortestpathweightsbutalsoapredecessormatrix
D.ij/,whereijisNILifeitheriDjorthereisnopathfromitoj,
andotherwiseijisthepredecessorofjonsomeshortestpathfromi.Justas
thepredecessorsubgraphGfromChapter24isashortestpathstreeforagiven
sourcevertex,thesubgraphinducedbytheithrowofthematrixshouldbea
shortestpathstreewithrooti.Foreachvertexi2V,wedefinethepredecessor
subgraphofGforiasGiD.ViEi/,where
ViDfj2VWijNILg[fig
y
EiDf.ijj/Wj2Vi figg:
IfGiisashortestpathstree,thenthefollowingprocedure,whichisamodified
versionofthePRINTPATHprocedurefromChapter22,printsashortestpathfrom
vertexitovertexj.

PRINTALLPAIRSSHORTESTPATH.ij/
1ifi==j
2 printi
3elseifij==NIL
4 printnopathfromitojexists
5elsePRINTALLPAIRSSHORTESTPATH.iij/
6 printj

Inordertohighlighttheessentialfeaturesoftheallpairsalgorithmsinthischapter,
wewon'tcoverthecreationandpropertiesofpredecessormatricesasextensively
aswedealtwithpredecessorsubgraphsinChapter24.Someoftheexercisescover
thebasics.

Pgina107

686 Chapter25AllPairsShortestPaths

Chapteroutline
Section25.1presentsadynamicprogrammingalgorithmbasedonmatrixmulti
plicationtosolvetheallpairsshortestpathsproblem.Usingthetechniqueofre
peatedsquaring,wecanachievearunningtimeof.V3lgV/.Section25.2gives
anotherdynamicprogrammingalgorithm,theFloydWarshallalgorithm,which
runsintime.V3/.Section25.2alsocoverstheproblemoffindingthetran
sitiveclosureofadirectedgraph,whichisrelatedtotheallpairsshortestpaths
problema.Finally,Section25.3presentsJohnson'salgorithm,whichsolvestheall
https://translate.googleusercontent.com/translate_f 66/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
pairsshortestpathsprobleminOV2lgVCVE/timeandisagoodchoicefor
large,sparsegraphs.
Beforeproceeding,weneedtoestablishsomeconventionsforadjacencymatrix
representations.First,weshallgenerallyassumethattheinputgraphGD.VE/
hasnvertices,sothatnDjVj.Second,weshallusetheconventionofdenoting
matricesbyuppercaseletters,suchasW,L,orD,andtheirindividualelements
bysubscriptedlowercaseletters,suchaswij,lij,ordij.Somematriceswillhave
parenthesizedsuperscripts,asinL.m/Dl .m/ .m/
Ij orD.m/Dd Ij ,toindicate
iterates.Finally,foragivennnmatrixA,weshallassumethatthevalueofnis
storedintheattributeA:rows.

25.1Shortestpathsandmatrixmultiplication

Thissectionpresentsadynamicprogrammingalgorithmfortheallpairsshortest
pathsproblemonadirectedgraphGD.VE/.Eachmajorloopofthedynamic
programwillinvokeanoperationthatisverysimilartomatrixmultiplication,so
thatthealgorithmwilllooklikerepeatedmatrixmultiplication.Weshallstartby
developinga.V4/timealgorithmfortheallpairsshortestpathsproblemand
thenimproveitsrunningtimeto.V3lgV/.
Beforeproceeding,letusbrieflyrecapthestepsgiveninChapter15fordevel
opingadynamicprogrammingalgorithm.

1.Characterizethestructureofanoptimalsolution.
2.Recursivelydefinethevalueofanoptimalsolution.
3.Computethevalueofanoptimalsolutioninabottomupfashion.

Wereservethefourthstepconstructinganoptimalsolutionfromcomputedin
formationfortheexercises.

Page108

25.1Shortestpathsandmatrixmultiplication 687

Thestructureofashortestpath
Westartbycharacterizingthestructureofanoptimalsolution.Fortheallpairs
shortestpathsproblemonagraphGD.VE/,wehaveproven(Lemma24.1)
thatallsubpathsofashortestpathareshortestpaths.Supposethatwerepresent
thegraphbyanadjacencymatrixWD.wij/.Considerashortestpathpfrom
vertexitovertexj,andsupposethatpcontainsatmostmedges.Assumingthat
therearenonegativeweightcycles,misfinite.IfiDj,thenphasweight0
andnoedges.Ifverticesiandjaredistinct,thenwedecomposepathpinto
p
yok!j,wherepathp
0 0nowcontainsatmostm1edges.ByLemma24.1,

p0isashortestpathfromitok,andso.ij/D.ik/Cwkj.

Arecursivesolutiontotheallpairsshortestpathsproblem
.m/ betheminimumweightofanypathfromvertexitovertexjthat
Now,letl Ij
containsatmostmedges.WhenmD0,thereisashortestpathfromitojwith
noedgesifandonlyifiDj.As,
(
.0/ 0 ifiDj
LIj re
1ifij:

Form 1,wecomputel Ij.m/ astheminimumofl Ij.m1/ (theweightofashortest


pathfromitojconsistingofatmostm1edges)andtheminimumweightofany
pathfromitojconsistingofatmostmedges,obtainedbylookingatallpossible
predecessorskofj.Thus,werecursivelydefine

LIj.m/ Dminl Ij .m1/ min L.m1/ Cwkj
1kn Ik

Dmin L.m1/ Cwkj : (25.2)
1kn Ik
ThelatterequalityfollowssincewjjD0forallj.
Whataretheactualshortestpathweights.ij/?Ifthegraphcontains
nonegativeweightcycles,thenforeverypairofverticesiandjforwhich
.ij/<1,thereisashortestpathfromitojthatissimpleandthuscontainsat
mostn1edges.Apathfromvertexitovertexjwithmorethann1edges
cannothavelowerweightthanashortestpathfromitoj.Theactualshortestpath
weightsarethereforegivenby
.ij/Dl .n1/ Dl .n/ Dl .nC1/ D: (25.3)
Ij Ij Ij

https://translate.googleusercontent.com/translate_f 67/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Page109

688 Chapter25AllPairsShortestPaths

Computingtheshortestpathweightsbottomup
TakingasourinputthematrixWD.wij/,wenowcomputeaseriesofmatrices
L.1/L.2/:::L.n1/,whereformD12:::norte 1,wehaveL.m/Dl .m/
Ij .
ThefinalmatrixL.n1/containstheactualshortestpathweights.Observethat
.1/ Dwijforallverticesij2V,andsoL.1/DW.
LIj
Theheartofthealgorithmisthefollowingprocedure,which,givenmatrices
L.m1/andW,returnsthematrixL.m/.Thatis,itextendstheshortestpathscom
putedsofarbyonemoreedge.

EXTENDSHORTESTPATHS.LW/
1nDL:rows
2letL0Dl0 beanewnnmatrix
Ij
3foriD1ton
4 forjD1ton
5 lij
0
D1
6 forkD1ton
7 lij
0
Dmin.l0 ijlikCwkj/
8returnL0

TheprocedurecomputesamatrixL0D.l0ij/,whichitreturnsattheend.Itdoesso
bycomputingequation(25.2)foralliandj,usingLforL.m1/andL0forL.m/.
(Itiswrittenwithoutthesuperscriptstomakeitsinputandoutputmatricesinde
pendentofm.)Itsrunningtimeis.n3/duetothethreenestedforloops.
Nowwecanseetherelationtomatrixmultiplication.Supposewewishtocom
putethematrixproductCDABoftwonnmatricesAandB.Then,for
ijD12:::n,wecompute
x norte
cijD aik bkj: (25.4)
kD1
Observethatifwemakethesubstitutions
l.m1/ !a
w!b
l.m/ !c
min!C
C!

inequation(25.2),weobtainequation(25.4).Thus,ifwemakethesechangesto
EXTENDSHORTESTPATHSandalsoreplace1(theidentityformin)by0(the

Pgina110

25.1Shortestpathsandmatrixmultiplication 689

identityforC),weobtainthesame.n3/timeprocedureformultiplyingsquare
matricesthatwesawinSection4.2:

SQUAREMATRIXMULTIPLY.AB/
1nDA:rows
2letCbeanewnnmatrix
3foriD1ton
4 forjD1ton
5 cijD0
6 forkD1ton
7 cijDcijCaik bkj
8returnC

Returningtotheallpairsshortestpathsproblem,wecomputetheshortestpath
weightsbyextendingshortestpathsedgebyedge.LettingABdenotethema
trixproductreturnedbyEXTENDSHORTESTPATHS.AB/,wecomputethese
quenceofn1matrices
L.1/ re L.0/W DW
L.2/ re L.1/W DW2

https://translate.googleusercontent.com/translate_f 68/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
L.3/ re L.2/W DW3
Unesdoc.unesco.orgunesdoc.unesco.org
L.n1/ DL.n2/WDWn1:
Aswearguedabove,thematrixL.n1/DWn1containstheshortestpathweights.
Thefollowingprocedurecomputesthissequencein.n4/time.

SLOWALLPAIRSSHORTESTPATHS.W/
1nDW:rows
2L.1/DW
3formD2ton1
4 letL.m/beanewnnmatrix
5 L.m/DEXTENDSHORTESTPATHS.L.m1/W/
6returnL.n1/

Figure25.1showsagraphandthematricesL.m/computedbytheprocedure
SLOWALLPAIRSSHORTESTPATHS.

Improvingtherunningtime
Ourgoal,however,isnottocomputealltheL.m/matrices:weareinterested
onlyinmatrixL.n1/.Recallthatintheabsenceofnegativeweightcycles,equa

Pgina111

690 Chapter25AllPairsShortestPaths

2
3 4
1 3
2 8

4 5
7 1
5 4
6

0 3 81 4 0 3 82 4
1 0 1 1 7 3 0 41 7
L.1/D 1 4 01 1 L.2/D 1 4 05 11
21 5 0 1 2 1 50 2
11 1 6 0 8 1 diecisis0

0 3 32 4 0 1 32 4
3 0 41 1 3 0 41 1
L.3/D 7 4 05 11 L.4/D 7 4 05 3
2 1 50 2 2 1 50 2
8 5 diecisis0 8 5 diecisis0

Figure25.1AdirectedgraphandthesequenceofmatricesL.m/computedbySLOWALLPAIRS
SHORTESTPATHS.YoumightwanttoverifythatL.5/,definedasL.4/W,equalsL.4/,andthus
L.m/DL.4/forallm 4.

tion(25.3)impliesL.m/DL.n1/forallintegersm norte1.Justastradi
tionalmatrixmultiplicationisassociative,soismatrixmultiplicationdefinedby
theEXTENDSHORTESTPATHSprocedure(seeExercise25.14).Therefore,we
cancomputeL.n1/withonlydlg.n1/ematrixproductsbycomputingthese
quence
L.1/ re W
L.2/ re W2 DWW
L.4/ re W4 DW2W2
L.8/ re W8 DW4W4
Unesdoc.unesco.orgunesdoc.unesco.org

L.2dlg.n1/e / DW2 dlg.n1/e DW2 dlg.n1/e1 W2 dlg.n1/e1 :

Since2dlg.n1/e n1,thefinalproductL.2 /isequaltoL.n1/. dlg.n1/e

Thefollowingprocedurecomputestheabovesequenceofmatricesbyusingthis
techniqueofrepeatedsquaring.

Pgina112

25.1Shortestpathsandmatrixmultiplication 691

1 2
https://translate.googleusercontent.com/translate_f 69/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
1 2 3
4 7 10 8
2 1 5
4 3 5 6

Figure25.2Aweighted,directedgraphforuseinExercises25.11,25.21,and25.31.

FASTERALLPAIRSSHORTESTPATHS.W/
1nDW:rows
2L.1/DW
3mD1
4whilem<n1
5 letL.2m/beanewnnmatrix
6 L.2m/DEXTENDSHORTESTPATHS.L.m/L.m//
7 mD2m
8returnL.m/

Ineachiterationofthewhileloopoflines47,wecomputeL.2m/DL.m/2,
startingwithmD1.Attheendofeachiteration,wedoublethevalue
ofm.ThefinaliterationcomputesL.n1/byactuallycomputingL.2m/forsome
n12m<2n2.Byequation(25.3),L.2m/DL.n1/.Thenexttimethetest
inline4isperformed,mhasbeendoubled,sonowm n1,thetestfails,and
theprocedurereturnsthelastmatrixitcomputed.
Becauseeachofthedlg.n1/ematrixproductstakes.n3/time,FASTER
ALLPAIRSSHORTESTPATHSrunsin.n3lgn/time.Observethatthecode
istight,containingnoelaboratedatastructures,andtheconstanthiddeninthe
notationisthereforesmall.

Exercises

25.11
RunSLOWALLPAIRSSHORTESTPATHSontheweighted,directedgraphof
Figure25.2,showingthematricesthatresultforeachiterationoftheloop.Then
dothesameforFASTERALLPAIRSSHORTESTPATHS.

25.12
WhydowerequirethatwiiD0forall1in?

Page113

692 Chapter25AllPairsShortestPaths

25.13
Whatdoesthematrix

011 1
101 1
L.0/D 110 1
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
111 0

usedintheshortestpathsalgorithmscorrespondtoinregularmatrixmultiplica
Cin

25.14
ShowthatmatrixmultiplicationdefinedbyEXTENDSHORTESTPATHSisasso
ciative.

25.15
Showhowtoexpressthesinglesourceshortestpathsproblemasaproductofma
tricesandavector.DescribehowevaluatingthisproductcorrespondstoaBellman
Fordlikealgorithm(seeSection24.1).

25.16
Supposewealsowishtocomputetheverticesonshortestpathsinthealgorithmsof
thissection.Showhowtocomputethepredecessormatrixfromthecompleted
matrixLofshortestpathweightsinOn3/time.

25.17
Wecanalsocomputetheverticesonshortestpathsaswecomputetheshortest
pathweights.Define Ij .m/ asthepredecessorofvertexjonanyminimumweight
pathfromitojthatcontainsatmostmedges.ModifytheEXTENDSHORTEST
PATHSandSLOWALLPAIRSSHORTESTPATHSprocedurestocomputethema
trices.1/.2/:::.n1/asthematricesL.1/L.2/:::L.n1/arecomputed.
https://translate.googleusercontent.com/translate_f 70/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

25.18
TheFASTERALLPAIRSSHORTESTPATHSprocedure,aswritten,requiresusto
storedlg.n1/ematrices,eachwithn2elements,foratotalspacerequirementof
.n2lgn/.Modifytheproceduretorequireonly.n2/spacebyusingonlytwo
nnmatrices.

25.19
ModifyFASTERALLPAIRSSHORTESTPATHSsothatitcandeterminewhether
thegraphcontainsanegativeweightcycle.

Pgina114

25.2TheFloydWarshallalgorithm 693

25.110
Giveanefficientalgorithmtofindthelength(numberofedges)ofaminimum
lengthnegativeweightcycleinagraph.

25.2TheFloydWarshallalgorithm

Inthissection,weshalluseadifferentdynamicprogrammingformulationtosolve
theallpairsshortestpathsproblemonadirectedgraphGD.VE/.Elresultado
ingalgorithm,knownastheFloydWarshallalgorithm,runsin.V3/time.Como
before,negativeweightedgesmaybepresent,butweassumethatthereareno
negativeweightcycles.AsinSection25.1,wefollowthedynamicprogramming
processtodevelopthealgorithm.Afterstudyingtheresultingalgorithm,we
presentasimilarmethodforfindingthetransitiveclosureofadirectedgraph.

Thestructureofashortestpath
IntheFloydWarshallalgorithm,wecharacterizethestructureofashortestpath
differentlyfromhowwecharacterizeditinSection25.1.TheFloydWarshallalgo
rithmconsiderstheintermediateverticesofashortestpath,whereanintermediate
vertexofasimplepathpDh12:::liisanyvertexofpotherthan1orl,
thatis,anyvertexinthesetf23:::l1g.
TheFloydWarshallalgorithmreliesonthefollowingobservation.Underour
assumptionthattheverticesofGareVDf12:::ng,letusconsiderasubset
f12:::kgofverticesforsomek.Foranypairofverticesij2V,considerall
pathsfromitojwhoseintermediateverticesarealldrawnfromf12:::kg,and
letpbeaminimumweightpathfromamongthem.(Pathpissimple.)TheFloyd
Warshallalgorithmexploitsarelationshipbetweenpathpandshortestpathsfromi
tojwithallintermediateverticesinthesetf12:::k1g.Larelacin
dependsonwhetherornotkisanintermediatevertexofpathp.
Ifkisnotanintermediatevertexofpathp,thenallintermediateverticesof
pathpareinthesetf12:::k1g.Thus,ashortestpathfromvertexi
tovertexjwithallintermediateverticesinthesetf12:::k1gisalsoa
shortestpathfromitojwithallintermediateverticesinthesetf12:::kg.
Ifkisanintermediatevertexofpathp,thenwedecomposepintoi k p p j,
1
2

asFigure25.3illustrates.ByLemma24.1,p1isashortestpathfromitok
withallintermediateverticesinthesetf12:::kg.Infact,wecanmakea
slightlystrongerstatement.Becausevertexkisnotanintermediatevertexof
pathp1,allintermediateverticesofp1areinthesetf12:::k1g.Ah

Pgina115

694 Chapter25AllPairsShortestPaths

allintermediateverticesinf12:::K
1g allintermediateverticesinf12:::K
1g

p K
1
p 2
J
yo

p:allintermediateverticesinf12:::kg

Figure25.3Pathpisashortestpathfromvertexitovertexj,andkisthehighestnumbered
intermediatevertexofp.Pathp1,theportionofpathpfromvertexitovertexk,hasallintermediate
verticesinthesetf12:::k1g.Thesameholdsforpathp2fromvertexktovertexj.

https://translate.googleusercontent.com/translate_f 71/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

fore,p1isashortestpathfromitokwithallintermediateverticesintheset
f12:::k1g.Similarly,p2isashortestpathfromvertexktovertexjwith
allintermediateverticesinthesetf12:::k1g.

Arecursivesolutiontotheallpairsshortestpathsproblem

Basedontheaboveobservations,wedefinearecursiveformulationofshortest
pathestimatesthatdiffersfromtheoneinSection25.1.Letd .k/ betheweight
Ij
ofashortestpathfromvertexitovertexjforwhichallintermediatevertices
areinthesetf12:::kg.WhenkD0,apathfromvertexitovertexjwith
nointermediatevertexnumberedhigherthan0hasnointermediateverticesatall.
Suchapathhasatmostoneedge,andhenced Ij.0/ Dwij.Followingtheabove
discussion,wedefined Ij.k/ recursivelyby
(
wij ifkD0
reIj.k/ re (25,5)
mind Ij.k1/ d Ik
.k1/ Cd .k1/
Kj ifk 1

Becauseforanypath,allintermediateverticesareinthesetf12:::ng,thema
trixD.n/Dd Ij.n/ givesthefinalanswer:d Ij.n/ D.ij/forallij2V.

Computingtheshortestpathweightsbottomup
Basedonrecurrence(25.5),wecanusethefollowingbottomupproceduretocom
putethevaluesdIj.k/ inorderofincreasingvaluesofk.ItsinputisannnmatrixW
definedasinequation(25.1).TheprocedurereturnsthematrixD.n/ofshortest
pathweights.

Pgina116

25.2TheFloydWarshallalgorithm 695

FLOYDWARSHALL.W/
1nDW:rows
2D.0/DW
3forkD1ton
4 letD.k/Dd Ij.k/ beanewnnmatrix
5 foriD1ton
6 forjD1ton
7 reIj.k/ Dmind Ij.k1/ d Ik
.k1/ Cd .k1/
Kj
8returnD.n/

Figure25.4showsthematricesD.k/computedbytheFloydWarshallalgorithm
forthegraphinFigure25.1.
TherunningtimeoftheFloydWarshallalgorithmisdeterminedbythetriply
nestedforloopsoflines37.Becauseeachexecutionofline7takesO.1/time,
thealgorithmrunsintime.n3/.AsinthefinalalgorithminSection25.1,the
codeistight,withnoelaboratedatastructures,andsotheconstanthiddeninthe
notationissmall.Thus,theFloydWarshallalgorithmisquitepracticalforeven
moderatesizedinputgraphs.

Constructingashortestpath
ThereareavarietyofdifferentmethodsforconstructingshortestpathsintheFloyd
Warshallalgorithm.OnewayistocomputethematrixDofshortestpathweights
andthenconstructthepredecessormatrixfromtheDmatrix.Exercise25.16
asksyoutoimplementthismethodsothatitrunsinOn3/time.Giventhepre
decessormatrix,thePRINTALLPAIRSSHORTESTPATHprocedurewillprint
theverticesonagivenshortestpath.
Alternatively,wecancomputethepredecessormatrixwhilethealgorithm
computesthematricesD.k/.Specifically,wecomputeasequenceofmatrices
.0/.1/:::.n/,whereD.n/andwedefine .k/
Ij asthepredecessorof
vertexjonashortestpathfromvertexiwithallintermediateverticesintheset
f12:::kg.
Wecangivearecursiveformulationof ij .k/
.WhenkD0,ashortestpathfromi
tojhasnointermediateverticesatall.As,
(
.0/ re NILifiDjorwijD1 (25.6)
Ij yo ifijandwij<1:

Fork 1,ifwetakethepathikj,wherekj,thenthepredecessor
ofjwechooseisthesameasthepredecessorofjwechoseonashortestpath
fromkwithallintermediateverticesinthesetf12:::k1g.Otherwise,we

https://translate.googleusercontent.com/translate_f 72/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina117

696 Chapter25AllPairsShortestPaths


0 3 81 4 NULO1 1 NULO1
1 0 1 1 7 NULO NULO2
NULO 2
D.0/D 1 4 01 1 .0/D NULO3 NULO
NULO
NULO
21 5 0 1 4 NULO4 NULO
NULO
11 1 6 0 NULO NULO5 NULO
NULO
0 3 81 4 NULO1 1 NULO1
1 0 1 1 7 NULO NULO2
NULO 2
D.1/D 1 4 01 1 .1/D NULO3 NULO
NULO
NULO
2 5 5 0 2 4 1 4 NULO1
11 1 6 0 NULO NULO5 NULO
NULO
0 3 84 4 NULO1 1 2 1
1 0 11 7 NULO NULO2
NULO 2
D.2/D 1 4 05 11 .2/D NULO3 NULO2 2
2 5 50 2 4 1 4 NULO1
11 diecisis 0 NULO NULO5 NULO
NULO
0 3 84 4 NULO1 1 2 1
1 0 11 7 NULO NULO2
NULO 2
D.3/D 1 4 05 11 .3/D NULO3 NULO2 2
2 1 50 2 4 3 4 NULO1
1 1 diecisis 0 NULO NULO5 NULO
NULO
0 3 14 4 NULO1 4 2 1
3 0 41 1 4 NULO4 2 1
D.4/D 7 4 05 3 .4/D 4 3 NULO2 1
2 1 50 2 4 3 4 NULO1
8 5 diecisis0 4 3 4 5 NULO

0 1 32 4 NULO3 4 5 1
3 0 41 1 4 NULO4 2 1
D.5/D 7 4 05 3 .5/D 4 3 NULO2 1
2 1 50 2 4 3 4 NULO1
8 5 diecisis0 4 3 4 5 NULO

Figure25.4ThesequenceofmatricesD.k/and.k/computedbytheFloydWarshallalgorithm
forthegraphinFigure25.1.

Pgina118

25.2TheFloydWarshallalgorithm 697

choosethesamepredecessorofjthatwechoseonashortestpathfromiwithall
intermediateverticesinthesetf12:::k1g.Formally,fork 1,
(
.k1/ ifd .k1/ d .k1/ Cd .k1/
.k/ re Ij Ij Ik Kj (25.7)
Ij .k1/ ifd .k1/ >d .k1/ Cd .k1/ :
Kj Ij Ik Kj
Weleavetheincorporationofthe.k/matrixcomputationsintotheFLOYD
WARSHALLprocedureasExercise25.23.Figure25.4showsthesequenceof.k/
matricesthattheresultingalgorithmcomputesforthegraphofFigure25.1.los
exercisealsoasksforthemoredifficulttaskofprovingthatthepredecessorsub
graphGiisashortestpathstreewithrooti.Exercise25.27asksforyetanother
waytoreconstructshortestpaths.

Transitiveclosureofadirectedgraph
GivenadirectedgraphGD.VE/withvertexsetVDf12:::ng,wemight
wishtodeterminewhetherGcontainsapathfromitojforallvertexpairs
ij2V.WedefinethetransitiveclosureofGasthegraphGD.VE/,where
EDfij/WthereisapathfromvertexitovertexjinGg:
Onewaytocomputethetransitiveclosureofagraphin.n3/timeistoassign
aweightof1toeachedgeofEandruntheFloydWarshallalgorithm.Sihayun
pathfromvertexitovertexj,wegetdij<n.Otherwise,wegetdijD1.

https://translate.googleusercontent.com/translate_f 73/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Thereisanother,similarwaytocomputethetransitiveclosureofGin.n3/
timethatcansavetimeandspaceinpractice.Thismethodsubstitutesthelogical
operations_(logicalOR)and^(logicalAND)forthearithmeticoperationsmin
andCintheFloydWarshallalgorithm.ForijkD12:::n,wedefinet .k/
Ij a
be1ifthereexistsapathingraphGfromvertexitovertexjwithallintermediate
verticesinthesetf12:::kg,and0otherwise.Weconstructthetransitiveclosure
GD.VE/byputtingedge.ij/intoEifandonlyift .n/
Ij D1.Arecursive
.k/
definitionoft ij ,analogoustorecurrence(25.5),is
(
.0/ re 0ifijand.ij/62E
TIj
1ifiDjor.ij/2E

andfork 1,
.k/ Dt .k1/ _t .k1/ ^t .k1/
TIj : (25.8)
Ij Ik Kj
AsintheFloydWarshallalgorithm,wecomputethematricesT.k/Dt .k/
Ij en
orderofincreasingk.

Pgina119

698 Chapter25AllPairsShortestPaths

1 2

4 3

1000 1000 1000


T.0/D 0111 T.1/D 0111 T.2/D 0111
0110 0110 0111
1011 1011 1011

1000 1000
T.3/D 0111 T.4/D 1111
0111 1111
1111 1111

Figure25.5AdirectedgraphandthematricesT.k/computedbythetransitiveclosurealgorithm.

TRANSITIVECLOSURE.G/
1nDjG:Vj
2letT.0/Dt .0/
Ij beanewnnmatrix
3foriD1ton
4 forjD1ton
5 ifi==jor.ij/2G:E
6 TIj.0/ D1
7 elset Ij.0/ D0
8forkD1ton
9 letT.k/Dt Ij.k/ beanewnnmatrix
10 foriD1ton
11 forjD1ton
12 TIj.k/ Dt Ij.k1/ _t .k1/ ^t .k1/
Ik Kj
13returnT.n/

Figure25.5showsthematricesT.k/computedbytheTRANSITIVECLOSURE
procedureonasamplegraph.TheTRANSITIVECLOSUREprocedure,likethe
FloydWarshallalgorithm,runsin.n3/time.Onsomecomputers,though,log
icaloperationsonsinglebitvaluesexecutefasterthanarithmeticoperationson
integerwordsofdata.Moreover,becausethedirecttransitiveclosurealgorithm
usesonlybooleanvaluesratherthanintegervalues,itsspacerequirementisless

Page120

25.2TheFloydWarshallalgorithm 699

thantheFloydWarshallalgorithm'sbyafactorcorrespondingtothesizeofaword
ofcomputerstorage.

https://translate.googleusercontent.com/translate_f 74/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Exercises
25.21
RuntheFloydWarshallalgorithmontheweighted,directedgraphofFigure25.2.
ShowthematrixD.k/thatresultsforeachiterationoftheouterloop.

25.22
ShowhowtocomputethetransitiveclosureusingthetechniqueofSection25.1.

25.23
ModifytheFLOYDWARSHALLproceduretocomputethe.k/matricesaccording
toequations(25.6)and(25.7).Proverigorouslythatforalli2V,thepredecessor
subgraphGiisashortestpathstreewithrooti.(Hint:ToshowthatGiis
acyclic,firstshowthat .k/ .k/ reil.k/ Cwlj,accordingtothe
Ij Dlimpliesd Ij
.k/
definitionof ij.Then,adapttheproofofLemma24.16.)

25.24
Asitappearsabove,theFloydWarshallalgorithmrequires.n3/space,sincewe
computed Ij.k/ forijkD12:::norte.Showthatthefollowingprocedure,which
simplydropsallthesuperscripts,iscorrect,andthusonly.n2/spaceisrequired.

FLOYDWARSHALL 0.W/
1nDW:rows
2DDW
3forkD1ton
4 foriD1ton
5 forjD1ton
6 dijDmin.dijdikCdkj/
7returnD

25.25
Supposethatwemodifythewayinwhichequation(25.7)handlesequality:
(
.k1/ ifd .k1/ <d .k1/ Cd .k1/
.k/ Ij Ij Ik Kj
Ij re .k1/ ifd .k1/ re.k1/ Cd .k1/ :
Kj Ij Ik Kj
Isthisalternativedefinitionofthepredecessormatrixcorrect?

Pgina121

700 Chapter25AllPairsShortestPaths

25.26
HowcanweusetheoutputoftheFloydWarshallalgorithmtodetectthepresence
ofanegativeweightcycle?

25.27
AnotherwaytoreconstructshortestpathsintheFloydWarshallalgorithmuses
valores .k/
Ij forijkD12:::n,where
.k/
Ij isthehighestnumberedinterme
diatevertexofashortestpathfromitojinwhichallintermediateverticesare
inthesetf12:::kg.Givearecursiveformulationfor .k/
ij,modifytheFLOYD
WARSHALLproceduretocomputethe .k/
Ij values,andrewritethePRINTALL
PAIRSSHORTESTPATHproceduretotakethematrixD .n/ asaninput.
Ij
Howisthematrixlikethestableinthematrixchainmultiplicationproblemof
Section15.2?

25.28
GiveanO.VE/timealgorithmforcomputingthetransitiveclosureofadirected
graphGD.VE/.

25.29
Supposethatwecancomputethetransitiveclosureofadirectedacyclicgraphin
f.jVjjEj/time,wherefisamonotonicallyincreasingfunctionofjVjandjEj.
ShowthatthetimetocomputethetransitiveclosureGD.VE/ofageneral
directedgraphGD.VE/isthenf.jVjjEj/COVCE/.

25.3Johnson'salgorithmforsparsegraphs

Johnson'salgorithmfindsshortestpathsbetweenallpairsinOV2lgVCVE/
hora.Forsparsegraphs,itisasymptoticallyfasterthaneitherrepeatedsquaringof
matricesortheFloydWarshallalgorithm.Thealgorithmeitherreturnsamatrixof
shortestpathweightsforallpairsofverticesorreportsthattheinputgraphcontains
anegativeweightcycle.Johnson'salgorithmusesassubroutinesbothDijkstras
algorithmandtheBellmanFordalgorithm,whichChapter24describes.

https://translate.googleusercontent.com/translate_f 75/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Johnson'salgorithmusesthetechniqueofreweighting,whichworksasfollows.
IfalledgeweightswinagraphGD.VE/arenonnegative,wecanfindshort
estpathsbetweenallpairsofverticesbyrunningDijkstra'salgorithmoncefrom
eachvertexwiththeFibonacciheapminpriorityqueue,therunningtimeofthis
allpairsalgorithmisOV2lgVCVE/.IfGhasnegativeweightedgesbutno
negativeweightcycles,wesimplycomputeanewsetofnonnegativeedgeweights

Page122

25.3Johnson'salgorithmforsparsegraphs 701

thatallowsustousethesamemethod.Thenewsetofedgeweightsywmustsatisfy
twoimportantproperties:
1.Forallpairsofverticesu2V,apathpisashortestpathfromutousing
weightfunctionwifandonlyifpisalsoashortestpathfromutousing
weightfunctionyw.
2.Foralledges.u/,thenewweightyw.u/isnonnegative.
Asweshallseeinamoment,wecanpreprocessGtodeterminethenewweight
functionywinO.VE/time.

Preservingshortestpathsbyreweighting
Thefollowinglemmashowshoweasilywecanreweighttheedgestosatisfythe
firstpropertyabove.Weusetodenoteshortestpathweightsderivedfromweight
functionwand Y todenoteshortestpathweightsderivedfromweightfunctionyw.

Lemma25.1(Reweightingdoesnotchangeshortestpaths)
Givenaweighted,directedgraphGD.VE/withweightfunctionwWE!R,
lethWV!Rbeanyfunctionmappingverticestorealnumbers.Foreachedge
.u/2E,define
yw.u/Dwu/Chu/h./: (25.9)
LetpDh01:::kibeanypathfromvertex0tovertexk.Thenpisa
shortestpathfrom0tokwithweightfunctionwifandonlyifitisashortestpath
withweightfunctionyw.Thatis,wp/D.0k/ifandonlyifyw.p/Dy.0k/.
Furthermore,Ghasanegativeweightcycleusingweightfunctionwifandonly
ifGhasanegativeweightcycleusingweightfunctionyw.

ProofWestartbyshowingthat
yw.p/Dwp/Ch.0/h.k/: (25.10)
Tenemos
xK
yw.p/D yw.i1i/
ID1
xK
re .w.i1i/Ch.i1/h.i//
ID1
xK
re w.i1i/Ch.0/h.k/ (becausethesumtelescopes)
ID1
Dwp/Ch.0/h.k/:

Pgina123

702 Chapter25AllPairsShortestPaths

Therefore,anypathpfrom0tokhasyw.p/Dwp/Ch.0/ marido.k/.Ser
causeh.0/andh.k/donotdependonthepath,ifonepathfrom0tokis
shorterthananotherusingweightfunctionw,thenitisalsoshorterusingyw.As,
wp/D.0k/ifandonlyifyw.p/Dy.0k/.
Finally,weshowthatGhasanegativeweightcycleusingweightfunctionwif
andonlyifGhasanegativeweightcycleusingweightfunctionyw.Considerany
cyclecDh01:::ki,where0Dk.Byequation(25.10),
yw.c/Dwc/Ch.0/h.k/
Dwc/
andthuschasnegativeweightusingwifandonlyifithasnegativeweightus
ingyw.

Producingnonnegativeweightsbyreweighting

https://translate.googleusercontent.com/translate_f 76/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Ournextgoalistoensurethatthesecondpropertyholds:wewantyw.u/tobe
nonnegativeforalledges.u/2E.Givenaweighted,directedgraphGD
.VE/withweightfunctionwWE!R,wemakeanewgraphG0D.V0E0/,
whereV0DV[fsgforsomenewvertexs62VandE0DE[fs/W2Vg.
Weextendtheweightfunctionwsothatws/D0forall 2V.Tengaencuentaque
becauseshasnoedgesthatenterit,noshortestpathsinG0,otherthanthosewith
sources,contains.Moreover,G0hasnonegativeweightcyclesifandonlyifG
hasnonegativeweightcycles.Figure25.6(a)showsthegraphG0corresponding
tothegraphGofFigure25.1.
NowsupposethatGandG0havenonegativeweightcycles.Letusdefine
marido./D.s/forall 2V0.Bythetriangleinequality(Lemma24.10),
wehaveh./hu/Cwu/foralledges.u/2E0.Thus,ifwede
finethenewweightsywbyreweightingaccordingtoequation(25.9),wehave
yw.u/Dwu/Chu/h./ 0,andwehavesatisfiedthesecondproperty.
Figure25.6(b)showsthegraphG0fromFigure25.6(a)withreweightededges.

Computingallpairsshortestpaths

Johnson'salgorithmtocomputeallpairsshortestpathsusestheBellmanFordal
gorithm(Section24.1)andDijkstra'salgorithm(Section24.3)assubroutines.Eso
assumesimplicitlythattheedgesarestoredinadjacencylists.Thealgorithmre
turnstheusualjVjjVjmatrixDDdij,wheredijD.ij/,oritreportsthat
theinputgraphcontainsanegativeweightcycle.Asistypicalforanallpairs
shortestpathsalgorithm,weassumethattheverticesarenumberedfrom1tojVj.

Pgina124

25.3Johnson'salgorithmforsparsegraphs 703

0 2 5 2
0 1 1 1
3 4 4 0
1 1
0 0 5 3 0 0 5 3
0 2 8 0 2 13

0 4 5 4 0 0
7 1 10 0
4 0 4 4 0 4
6 2
0 5 0 5

(un) (segundo)
2 2 2
2/1 0/0 0/4
4 0 4 0 4 0
1 3 1 3 1 3
0/0 2/3 2/3 0/4 2/7 0/0
2 13 2 13 2 13
0 0 0 0 0 0
10 0 10 0 10 0
0/4 2/2 2/1 0/1 2/3 0/5
2 2 2
5 4 5 4 5 4
(do) (re) (mi)
2 2
0/1 2/5
4 0 4 0
1 3 1 3
2/2 0/5 4/8 2/1
2 13 2 13
0 0 0 0
10 0 10 0
2/2 0/0 0/0 2/6
2 2
5 4 5 4
(f) (gramo)

Figure25.6Johnson'sallpairsshortestpathsalgorithmrunonthegraphofFigure25.1.Ver
texnumbersappearoutsidethevertices.(a)ThegraphG0withtheoriginalweightfunctionw.
Thenewvertexsisblack.Withineachvertex ish./D.s/.(b)Afterreweightingeach
edge.u/withweightfunctionyw.u/Dwu/Chu/h./.(c)(g)Theresultofrunning
Dijkstra'salgorithmoneachvertexofGusingweightfunctionwy.Ineachpart,thesourcevertexu
isblack,andshadededgesareintheshortestpathstreecomputedbythealgorithm.Withineach
vertexarethevaluesy.u/and.u/,separatedbyaslash.ThevalueduD.u/isequalto
y./Ch./hu/
u .

https://translate.googleusercontent.com/translate_f 77/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Pgina125
704 Chapter25AllPairsShortestPaths

JOHNSON.Gw/
1computeG0,whereG0:VDG:V[fsg,
G0:EDG:E[fs/W2G:Vg,and
ws/D0forall2G:V
2ifBELLMANFORD.G0ws/==FALSE
3 printtheinputgraphcontainsanegativeweightcycle
4elseforeachvertex2G0:V
5 seth./tothevalueof.s/
computedbytheBellmanFordalgorithm
6 foreachedge.u/2G0:E
7 yw.u/Dwu/Chu/h./
8 letDD.du/beanewnnmatrix
9 foreachvertexu2G:V
10 runDIJKSTRA.Gywu/tocompute Y.u/forall2G:V
11 foreachvertex2G:V
12 duDy.u/Ch./hu/
13 returnD

Thiscodesimplyperformstheactionswespecifiedearlier.Line1producesG0.
Line2runstheBellmanFordalgorithmonG0withweightfunctionwandsource
vertexs.IfG0,andhenceG,containsanegativeweightcycle,line3reportsthe
problema.Lines412assumethatG0containsnonegativeweightcycles.Lines45
seth./totheshortestpathweight.s/computedbytheBellmanFordalgo
rithmforall2V0.Lines67computethenewweightsyw.Foreachpairofver
Y
ticesu2V,theforloopoflines912computestheshortestpathweight .u/
bycallingDijkstra'salgorithmoncefromeachvertexinV.Line12storesin
matrixentryduthecorrectshortestpathweight.u/,calculatedusingequa
tion(25.10).Finally,line13returnsthecompletedDmatrix.Figure25.6depicts
theexecutionofJohnson'salgorithm.
IfweimplementtheminpriorityqueueinDijkstra'salgorithmbyaFibonacci
heap,Johnson'salgorithmrunsinOV2lgVCVE/time.Thesimplerbinarymin
heapimplementationyieldsarunningtimeofO.VElgV/,whichisstillasymp
toticallyfasterthantheFloydWarshallalgorithmifthegraphissparse.

Exercises

25.31
UseJohnson'salgorithmtofindtheshortestpathsbetweenallpairsofverticesin
thegraphofFigure25.2.Showthevaluesofhandywcomputedbythealgorithm.

Pgina126

ProblemsforChapter25 705

25.32
WhatisthepurposeofaddingthenewvertexstoV,yieldingV0?

25.33
Supposethatwu/ 0foralledges.u/2E.Whatistherelationship
betweentheweightfunctionswandyw?

25.34
ProfessorGreenstreetclaimsthatthereisasimplerwaytoreweightedgesthan
themethodusedinJohnson'salgorithm.LettingwDmin.u/2Efw.u/g,just
defineyw.u/Dwu/wforalledges.u/2E.Whatiswrongwiththe
professor'smethodofreweighting?

25.35
SupposethatwerunJohnson'salgorithmonadirectedgraphGwithweightfunc
tionw.ShowthatifGcontainsa0weightcyclec,thenyw.u/D0forevery
edge.u/inc.

25.36
ProfessorMichenerclaimsthatthereisnoneedtocreateanewsourcevertexin
line1ofJOHNSON.HeclaimsthatinsteadwecanjustuseG0DGandletsbeany
vertex.Giveanexampleofaweighted,directedgraphGforwhichincorporating
theprofessor'sideaintoJOHNSONcausesincorrectanswers.ThenshowthatifG
isstronglyconnected(everyvertexisreachablefromeveryothervertex),theresults
returnedbyJOHNSONwiththeprofessor'smodificationarecorrect.

https://translate.googleusercontent.com/translate_f 78/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Problemas

251Transitiveclosureofadynamicgraph
SupposethatwewishtomaintainthetransitiveclosureofadirectedgraphGD
.VE/asweinsertedgesintoE.Thatis,aftereachedgehasbeeninserted,we
wanttoupdatethetransitiveclosureoftheedgesinsertedsofar.Assumethatthe
graphGhasnoedgesinitiallyandthatwerepresentthetransitiveclosureasa
booleanmatrix.
a.ShowhowtoupdatethetransitiveclosureGD.VE/ofagraphGD.VE/
inOV2/timewhenanewedgeisaddedtoG.

segundo.GiveanexampleofagraphGandanedgeesuchthat.V2/timeisrequired
toupdatethetransitiveclosureaftertheinsertionofeintoG,nomatterwhat
algorithmisused.

Page127

706 Chapter25AllPairsShortestPaths

do.Describeanefficientalgorithmforupdatingthetransitiveclosureasedgesare
insertedintothegraph.Foranysequenceofninsertions,youralgorithmshould
Pn
runintotaltime iD1tiDOV3/,wheretiisthetimetoupdatethetransitive
closureuponinsertingtheithedge.Provethatyouralgorithmattainsthistime
ligado.

252Shortestpathsindensegraphs
AgraphGD.VE/isdenseifjEjD.V1C/forsomeconstantinthe
range0<1.Byusingdaryminheaps(seeProblem62)inshortestpaths
algorithmsondensegraphs,wecanmatchtherunningtimesofFibonacciheap
basedalgorithmswithoutusingascomplicatedadatastructure.

a.WhataretheasymptoticrunningtimesforINSERT,EXTRACTMIN,and
DECREASEKEY,asafunctionofdandthenumbernofelementsinadary
minheap?WhataretheserunningtimesifwechoosedD.n/forsome
constant0<1?Comparetheserunningtimestotheamortizedcostsof
theseoperationsforaFibonacciheap.

segundo.Showhowtocomputeshortestpathsfromasinglesourceonandensedirected
graphGD.VE/withnonegativeweightedgesinOE/time.(Hint:Pickd
asafunctionof.)

do.Showhowtosolvetheallpairsshortestpathsproblemonandensedirected
graphGD.VE/withnonegativeweightedgesinO.VE/time.

re.ShowhowtosolvetheallpairsshortestpathsprobleminO.VE/timeonan
densedirectedgraphGD.VE/thatmayhavenegativeweightedgesbut
hasnonegativeweightcycles.

Chapternotes

Lawler[224]hasagooddiscussionoftheallpairsshortestpathsproblem,al
thoughhedoesnotanalyzesolutionsforsparsegraphs.Heattributesthematrix
multiplicationalgorithmtothefolklore.TheFloydWarshallalgorithmisdueto
Floyd[105],whobaseditonatheoremofWarshall[349]thatdescribeshowto
computethetransitiveclosureofbooleanmatrices.Johnson'salgorithmistaken
from[192].
Severalresearchershavegivenimprovedalgorithmsforcomputingshortest
pathsviamatrixmultiplication.Fredman[111]showshowtosolvetheall
pairsshortestpathsproblemusingOV5=2/comparisonsbetweensumsofedge

Pgina128

NotesforChapter25 707

weightsandobtainsanalgorithmthatrunsinOV3.lglgV=lgV/1=3/time,which
isslightlybetterthantherunningtimeoftheFloydWarshallalgorithm.Han[159]
reducedtherunningtimetoOV3.lglgV=lgV/5=4/.Anotherlineofresearch
demonstratesthatwecanapplyalgorithmsforfastmatrixmultiplication(seethe
chapternotesforChapter4)totheallpairsshortestpathsproblem.LetOn!/be
therunningtimeofthefastestalgorithmformultiplyingnnmatricesactualmente
!<2:376[78].GalilandMargalit[123,124]andSeidel[308]designedalgo

https://translate.googleusercontent.com/translate_f 79/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
rithmsthatsolvetheallpairsshortestpathsprobleminundirected,unweighted
graphsin.V!pV//time,wherepn/denotesaparticularfunctionthatispoly
logarithmicallyboundedinn.Indensegraphs,thesealgorithmsarefasterthan
theO.VE/timeneededtoperformjVjbreadthfirstsearches.Severalresearchers
haveextendedtheseresultstogivealgorithmsforsolvingtheallpairsshortest
pathsprobleminundirectedgraphsinwhichtheedgeweightsareintegersinthe
rangef12:::Wg.Theasymptoticallyfastestsuchalgorithm,byShoshanand
Zwick[316],runsintimeOWV!pVW//.
Karger,Koller,andPhillips[196]andindependentlyMcGeoch[247]havegiven
atimeboundthatdependsonE,thesetofedgesinEthatparticipateinsome
shortestpath.Givenagraphwithnonnegativeedgeweights,theiralgorithmsrunin
O.VECV2lgV/timeandimproveuponrunningDijkstra'salgorithmjVjtimes
whenjEjDoE/.
Baswana,Hariharan,andSen[33]examineddecrementalalgorithmsformain
tainingallpairsshortestpathsandtransitiveclosureinformation.Decremen
talalgorithmsallowasequenceofintermixededgedeletionsandqueriespor
comparison,Problem251,inwhichedgesareinserted,asksforanincremen
talalgorithm.ThealgorithmsbyBaswana,Hariharan,andSenarerandomized
and,whenapathexists,theirtransitiveclosurealgorithmcanfailtoreportit
withprobability1=ncforanarbitraryc>0.ThequerytimesareO.1/with
highprobability.Fortransitiveclosure,theamortizedtimeforeachupdateis
OV4=3lg1=3V/.Forallpairsshortestpaths,theupdatetimesdependonthe
Consultas.Forqueriesjustgivingtheshortestpathweights,theamortizedtimeper
updateisOV3=Elg2V/.Toreporttheactualshortestpath,theamortizedup
datetimeismin.OV3=2p lgV/OV3=Elg2V//.DemetrescuandItaliano[84]
showedhowtohandleupdateandqueryoperationswhenedgesarebothinserted
anddeleted,aslongaseachgivenedgehasaboundedrangeofpossiblevalues
drawnfromtherealnumbers.
Aho,Hopcroft,andUllman[5]definedanalgebraicstructureknownasaclosed
semiring,whichservesasageneralframeworkforsolvingpathproblemsindi
rectedgraphs.BoththeFloydWarshallalgorithmandthetransitiveclosurealgo
rithmfromSection25.2areinstantiationsofanallpairsalgorithmbasedonclosed
semirings.MaggsandPlotkin[240]showedhowtofindminimumspanningtrees
usingaclosedsemiring.

Pgina129

26 MaximumFlow

Justaswecanmodelaroadmapasadirectedgraphinordertofindtheshortest
pathfromonepointtoanother,wecanalsointerpretadirectedgraphasaflow
networkanduseittoanswerquestionsaboutmaterialflows.Imagineamate
rialcoursingthroughasystemfromasource,wherethematerialisproduced,to
asink,whereitisconsumed.Thesourceproducesthematerialatsomesteady
rate,andthesinkconsumesthematerialatthesamerate.Theflowofthemate
rialatanypointinthesystemisintuitivelytherateatwhichthematerialmoves.
Flownetworkscanmodelmanyproblems,includingliquidsflowingthroughpipes,
partsthroughassemblylines,currentthroughelectricalnetworks,andinformation
throughcommunicationnetworks.
Wecanthinkofeachdirectededgeinaflownetworkasaconduitforthemate
RialEachconduithasastatedcapacity,givenasamaximumrateatwhichthema
terialcanflowthroughtheconduit,suchas200gallonsofliquidperhourthrough
apipeor20amperesofelectricalcurrentthroughawire.Verticesareconduit
junctions,andotherthanthesourceandsink,materialflowsthroughthevertices
withoutcollectinginthem.Inotherwords,therateatwhichmaterialentersaver
texmustequaltherateatwhichitleavesthevertex.Wecallthispropertyflow
conservation,anditisequivalenttoKirchhoff'scurrentlawwhenthematerialis
electricalcurrent.
Inthemaximumflowproblem,wewishtocomputethegreatestrateatwhich
wecanshipmaterialfromthesourcetothesinkwithoutviolatinganycapacity
Restricciones.Itisoneofthesimplestproblemsconcerningflownetworksand,as
weshallseeinthischapter,thisproblemcanbesolvedbyefficientalgorithms.
Moreover,wecanadaptthebasictechniquesusedinmaximumflowalgorithmsto
solveothernetworkflowproblems.
Thischapterpresentstwogeneralmethodsforsolvingthemaximumflowprob

https://translate.googleusercontent.com/translate_f 80/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
LemSection26.1formalizesthenotionsofflownetworksandflows,formally
definingthemaximumflowproblem.Section26.2describestheclassicalmethod
ofFordandFulkersonforfindingmaximumflows.Anapplicationofthismethod,

Pgina130

26.1Flownetworks 709

findingamaximummatchinginanundirectedbipartitegraph,appearsinSec
tion26.3.Section26.4presentsthepushrelabelmethod,whichunderliesmanyof
thefastestalgorithmsfornetworkflowproblems.Section26.5coverstherelabel
tofrontalgorithm,aparticularimplementationofthepushrelabelmethodthat
runsintimeOV3/.Althoughthisalgorithmisnotthefastestalgorithmknown,
itillustratessomeofthetechniquesusedintheasymptoticallyfastestalgorithms,
anditisreasonablyefficientinpractice.

26.1Flownetworks

Inthissection,wegiveagraphtheoreticdefinitionofflownetworks,discusstheir
properties,anddefinethemaximumflowproblemprecisely.Wealsointroduce
somehelpfulnotation.

Flownetworksandflows

AflownetworkGD.VE/isadirectedgraphinwhicheachedge.u/2E
hasanonnegativecapacitycu/ 0.WefurtherrequirethatifEcontainsan
edge.u/,thenthereisnoedge.u/inthereversedirection.(Weshallsee
shortlyhowtoworkaroundthisrestriction.)If.u/62E,thenforconvenience
wedefinecu/D0,andwedisallowselfloops.Wedistinguishtwovertices
inaflownetwork:asourcesandasinkt.Forconvenience,weassumethateach
vertexliesonsomepathfromthesourcetothesink.Thatis,foreachvertex2V,
theflownetworkcontainsapaths t.Thegraphisthereforeconnected
and,sinceeachvertexotherthanshasatleastoneenteringedge,jEjjVj1.
Figure26.1showsanexampleofaflownetwork.
Wearenowreadytodefineflowsmoreformally.LetGD.VE/beaflow
networkwithacapacityfunctionc.Letsbethesourceofthenetwork,andlettbe
thesink.AflowinGisarealvaluedfunctionfWV V!Rthatsatisfiesthe
followingtwoproperties:

Capacityconstraint:Forallu2V,werequire0f.u/cu/.
Flowconservation:Forallu2V fstg,werequire
x x
f.u/D f.u/:
2V 2V
When.u/62E,therecanbenoflowfromuto,andf.u/D0.

Pgina131

710 Chapter26MaximumFlow

Edmonton Saskatoon
v1 12 v3 v1 12/12 v3 15/20
Vancouver diecisis 20 Winnipeg 11/16
S 4 9 7 T S 1/4 4/9 7/7 T
13 4 8/13
v2 v4 v2 v4 4/4
14 11/14
Calgary Regina
(un) (segundo)

Figure26.1(a)AflownetworkGD.VE/fortheLuckyPuckCompany'struckingproblem.
TheVancouverfactoryisthesources,andtheWinnipegwarehouseisthesinkt.Thecompanyships
pucksthroughintermediatecities,butonlycu/cratesperdaycangofromcityutocity.Cada
edgeislabeledwithitscapacity.(b)AflowfinGwithvaluejfjD19.Eachedge.u/islabeled
byf.u/=cu/.Theslashnotationmerelyseparatestheflowandcapacityitdoesnotindicate
divisin.

Wecallthenonnegativequantityf.u/theflowfromvertexutovertex.los

https://translate.googleusercontent.com/translate_f 81/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
valuejfjofaflowfisdefinedas
x x
jfjD f.s/ f.s/ (26.1)
2V 2V
thatis,thetotalflowoutofthesourceminustheflowintothesource.(Here,thejj
notationdenotesflowvalue,notabsolutevalueorcardinality.)Typically,aflow
networkwillnothaveanyedgesintothesource,andtheflowintothesource,given
PAG
bythesummation 2Vf. s/,willbe0.Weincludeit,however,becausewhen
weintroduceresidualnetworkslaterinthischapter,theflowintothesourcewill
becomesignificant.Inthemaximumflowproblem,wearegivenaflownetworkG
withsourcesandsinkt,andwewishtofindaflowofmaximumvalue.
Beforeseeinganexampleofanetworkflowproblem,letusbrieflyexplorethe
definitionofflowandthetwoflowproperties.Thecapacityconstraintsimply
saysthattheflowfromonevertextoanothermustbenonnegativeandmustnot
exceedthegivencapacity.Theflowconservationpropertysaysthatthetotalflow
intoavertexotherthanthesourceorsinkmustequalthetotalflowoutofthat
vertexinformally,flowinequalsflowout.

Anexampleofflow
AflownetworkcanmodelthetruckingproblemshowninFigure26.1(a).los
LuckyPuckCompanyhasafactory(sources)inVancouverthatmanufactures
hockeypucks,andithasawarehouse(sinkt)inWinnipegthatstocksthem.Suerte

Page132

26.1Flownetworks 711

v1 12 v3 v1 12 v3
20 20
diecisis diecisis
10
S 10 4 9 7 T S v 4 9 7 T
10
13 4 13 4
v2 v4 v2 v4
14 14

(un) (segundo)

Figure26.2Convertinganetworkwithantiparalleledgestoanequivalentonewithnoantiparallel
edges.(a)Aflownetworkcontainingboththeedges.12/and.21/.(b)Anequivalentnetwork
withnoantiparalleledges.Weaddthenewvertex0,andwereplaceedge.12/bythepairof
edges.10/and.02/,bothwiththesamecapacityas.12/.

Puckleasesspaceontrucksfromanotherfirmtoshipthepucksfromthefactory
tothewarehouse.Becausethetruckstraveloverspecifiedroutes(edges)between
cities(vertices)andhavealimitedcapacity,LuckyPuckcanshipatmostcu/
cratesperdaybetweeneachpairofcitiesuandinFigure26.1(a).LuckyPuck
hasnocontrolovertheseroutesandcapacities,andsothecompanycannotalter
theflownetworkshowninFigure26.1(a).Theyneedtodeterminethelargest
numberpofcratesperdaythattheycanshipandthentoproducethisamount,since
thereisnopointinproducingmorepucksthantheycanshiptotheirwarehouse.
LuckyPuckisnotconcernedwithhowlongittakesforagivenpucktogetfrom
thefactorytothewarehousetheycareonlythatpcratesperdayleavethefactory
andpcratesperdayarriveatthewarehouse.
Wecanmodeltheflowofshipmentswithaflowinthisnetworkbecausethe
numberofcratesshippedperdayfromonecitytoanotherissubjecttoacapacity
constraint.Additionally,themodelmustobeyflowconservation,forinasteady
state,therateatwhichpucksenteranintermediatecitymustequaltherateatwhich
theyleave.Otherwise,crateswouldaccumulateatintermediatecities.

Modelingproblemswithantiparalleledges
SupposethatthetruckingfirmofferedLuckyPucktheopportunitytoleasespace
for10cratesintrucksgoingfromEdmontontoCalgary.Itwouldseemnaturalto
addthisopportunitytoourexampleandformthenetworkshowninFigure26.2(a).
Thisnetworksuffersfromoneproblem,however:itviolatesouroriginalassump
tionthatifanedge.12/2E,then.21/62E.Wecallthetwoedges.12/
Y.21/antiparallel.Thus,ifwewishtomodelaflowproblemwithantipar
alleledges,wemusttransformthenetworkintoanequivalentonecontainingno

Pgina133

712 Chapter26MaximumFlow

https://translate.googleusercontent.com/translate_f 82/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

antiparalleledges.Figure26.2(b)displaysthisequivalentnetwork.Wechoose
oneofthetwoantiparalleledges,inthiscase.12/,andsplititbyaddinganew
vertex0andreplacingedge.12/withthepairofedges.10/and.02/.
Wealsosetthecapacityofbothnewedgestothecapacityoftheoriginaledge.
Theresultingnetworksatisfiesthepropertythatifanedgeisinthenetwork,the
reverseedgeisnot.Exercise26.11asksyoutoprovethattheresultingnetworkis
equivalenttotheoriginalone.
Thus,weseethatarealworldflowproblemmightbemostnaturallymodeled
byanetworkwithantiparalleledges.Itwillbeconvenienttodisallowantipar
alleledges,however,andsowehaveastraightforwardwaytoconvertanetwork
containingantiparalleledgesintoanequivalentonewithnoantiparalleledges.

Networkswithmultiplesourcesandsinks
Amaximumflowproblemmayhaveseveralsourcesandsinks,ratherthanjust
oneofeach.TheLuckyPuckCompany,forexample,mightactuallyhaveaset
ofmfactoriesfs1s2:::smgandasetofnwarehousesft1t2:::tng,asshown
inFigure26.3(a).Fortunately,thisproblemisnoharderthanordinarymaximum
fluir.
Wecanreducetheproblemofdeterminingamaximumflowinanetworkwith
multiplesourcesandmultiplesinkstoanordinarymaximumflowproblem.Higo
ure26.3(b)showshowtoconvertthenetworkfrom(a)toanordinaryflownetwork
withonlyasinglesourceandasinglesink.Weaddasupersourcesandadda
directededge.ssi/withcapacitycssi/D1foreachiD12:::metro.Nosotrostambin
createanewsupersinktandaddadirectededge.tit/withcapacityctit/D1
foreachiD12:::norte.Intuitively,anyflowinthenetworkin(a)correspondsto
aflowinthenetworkin(b),andviceversa.Thesinglesourcessimplyprovides
asmuchflowasdesiredforthemultiplesourcessi,andthesinglesinktlikewise
consumesasmuchflowasdesiredforthemultiplesinksti.Exercise26.12asks
youtoproveformallythatthetwoproblemsareequivalent.

Exercises

26.11
Showthatsplittinganedgeinaflownetworkyieldsanequivalentnetwork.Ms
formally,supposethatflownetworkGcontainsedge.u/,andwecreateanew
flownetworkG0bycreatinganewvertexxandreplacing.u/bynewedges
.ux/and.x/withcux/Dcx/Dcu/.Showthatamaximumflow
inG0hasthesamevalueasamaximumflowinG.

Pgina134

26.1Flownetworks 713

s1 s1
10 10
12 12
3 3
s2 t1 s2 t1
15 15
5 5
8 8
6 6
s3 t2
S s3 t2
T
20 20
14 14

7 7
13 13
s4 s4
t3 t3

18 18
11 11
2 2
s5 s5
(un) (segundo)

Figure26.3Convertingamultiplesource,multiplesinkmaximumflowproblemintoaproblem
withasinglesourceandasinglesink.(a)AflownetworkwithfivesourcesSDfs1s2s3s4s5g
andthreesinksTDft1t2t3g.(b)Anequivalentsinglesource,singlesinkflownetwork.Weadd
asupersourcesandanedgewithinfinitecapacityfromstoeachofthemultiplesources.Nosotrostambin
addasupersinktandanedgewithinfinitecapacityfromeachofthemultiplesinkstot.

26.12
Extendtheflowpropertiesanddefinitionstothemultiplesource,multiplesink
problema.Showthatanyflowinamultiplesource,multiplesinkflownetwork

https://translate.googleusercontent.com/translate_f 83/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
correspondstoaflowofidenticalvalueinthesinglesource,singlesinknetwork
obtainedbyaddingasupersourceandasupersink,andviceversa.

26.13
SupposethataflownetworkGD.VE/violatestheassumptionthatthenetwork
containsapathstforallvertices2V.Letubeavertexforwhichthere
isnopathsut.ShowthattheremustexistamaximumflowfinGsuch
thatf.u/Df.u/D0forallvertices2V.

Page135

714 Chapter26MaximumFlow

26.14
Letfbeaflowinanetwork,andletbearealnumber.Thescalarflowproduct,
denotedf,isafunctionfromV VtoRdefinedby
.f/.u/Df.u/:
Provethattheflowsinanetworkformaconvexset.Thatis,showthatiff1andf2
areflows,thensoisf1C.1/f2forallintherange01.

26.15
Statethemaximumflowproblemasalinearprogrammingproblem.

26.16
ProfessorAdamhastwochildrenwho,unfortunately,dislikeeachother.Theprob
lemissoseverethatnotonlydotheyrefusetowalktoschooltogether,butinfact
eachonerefusestowalkonanyblockthattheotherchildhassteppedonthatday.
Thechildrenhavenoproblemwiththeirpathscrossingatacorner.Fortunately
boththeprofessor'shouseandtheschoolareoncorners,butbeyondthatheisnot
sureifitisgoingtobepossibletosendbothofhischildrentothesameschool.
Theprofessorhasamapofhistown.Showhowtoformulatetheproblemofde
terminingwhetherbothhischildrencangotothesameschoolasamaximumflow
problema.

26.17
Supposethat,inadditiontoedgecapacities,aflownetworkhasvertexcapacities.
Thatiseachvertexhasalimitl./onhowmuchflowcanpassthough.Mostrar
howtotransformaflownetworkGD.VE/withvertexcapacitiesintoanequiv
alentflownetworkG0D.V0E0/withoutvertexcapacities,suchthatamaximum
flowinG0hasthesamevalueasamaximumflowinG.Howmanyverticesand
edgesdoesG0have?

26.2TheFordFulkersonmethod

ThissectionpresentstheFordFulkersonmethodforsolvingthemaximumflow
problema.Wecallitamethodratherthananalgorithmbecauseitencompasses
severalimplementationswithdifferingrunningtimes.TheFordFulkersonmethod
dependsonthreeimportantideasthattranscendthemethodandarerelevantto
manyflowalgorithmsandproblems:residualnetworks,augmentingpaths,and
CortesTheseideasareessentialtotheimportantmaxflowmincuttheorem(The
orem26.6),whichcharacterizesthevalueofamaximumflowintermsofcutsof

Page136

26.2TheFordFulkersonmethod 715

theflownetwork.Weendthissectionbypresentingonespecificimplementation
oftheFordFulkersonmethodandanalyzingitsrunningtime.
TheFordFulkersonmethoditerativelyincreasesthevalueoftheflow.Westart
withf.u/D0forallu2V,givinganinitialflowofvalue0.Ateach
iteration,weincreasetheflowvalueinGbyfindinganaugmentingpathinan
associatedresidualnetworkGf.Onceweknowtheedgesofanaugmenting
pathinGf,wecaneasilyidentifyspecificedgesinGforwhichwecanchange
theflowsothatweincreasethevalueoftheflow.Althougheachiterationofthe
FordFulkersonmethodincreasesthevalueoftheflow,weshallseethattheflow
onanyparticularedgeofGmayincreaseordecreasedecreasingtheflowonsome

https://translate.googleusercontent.com/translate_f 84/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
edgesmaybenecessaryinordertoenableanalgorithmtosendmoreflowfromthe
sourcetothesink.Werepeatedlyaugmenttheflowuntiltheresidualnetworkhas
nomoreaugmentingpaths.Themaxflowmincuttheoremwillshowthatupon
termination,thisprocessyieldsamaximumflow.

FORDFULKERSONMETHOD.Gst/
1initializeflowfto0
2whilethereexistsanaugmentingpathpintheresidualnetworkGf
3 augmentflowfalongp
4returnf

InordertoimplementandanalyzetheFordFulkersonmethod,weneedtointro
duceseveraladditionalconcepts.

Residualnetworks
Intuitively,givenaflownetworkGandaflowf,theresidualnetworkGfconsists
ofedgeswithcapacitiesthatrepresenthowwecanchangetheflowonedgesofG.
Anedgeoftheflownetworkcanadmitanamountofadditionalflowequaltothe
edge'scapacityminustheflowonthatedge.Ifthatvalueispositive,weplace
thatedgeintoGfwitharesidualcapacityofcf.u/Dcu/ f.u/.
TheonlyedgesofGthatareinGfarethosethatcanadmitmoreflowthose
edges.u/whoseflowequalstheircapacityhavecf.u/D0,andtheyarenot
inGf.
TheresidualnetworkGfmayalsocontainedgesthatarenotinG,however.
Asanalgorithmmanipulatestheflow,withthegoalofincreasingthetotalflow,it
mightneedtodecreasetheflowonaparticularedge.Inordertorepresentapos
sibledecreaseofapositiveflowf.u/onanedgeinG,weplaceanedge.u/
intoGfwithresidualcapacitycf.u/Df.u/thatis,anedgethatcanadmit
flowintheoppositedirectionto.u/,atmostcancelingouttheflowon.u/.
Thesereverseedgesintheresidualnetworkallowanalgorithmtosendbackflow

Page137

716 Chapter26MaximumFlow

ithasalreadysentalonganedge.Sendingflowbackalonganedgeisequiva
lenttodecreasingtheflowontheedge,whichisanecessaryoperationinmany
Algoritmos
Moreformally,supposethatwehaveaflownetworkGD.VE/withsources
andsinkt.LetfbeaflowinG,andconsiderapairofverticesu2V.Nosotros
Un
definetheresidualcapacityc f .u/by

cu/f.u/if.u/2E
cf.uD f.u/ if.u/2E (26.2)
0 otherwise:
Becauseofourassumptionthat.u/2Eimplies.u/62E,exactlyonecasein
equation(26.2)appliestoeachorderedpairofvertices.
Asanexampleofequation(26.2),ifcu/D16andf.u/D11,thenwe
canincreasef.u/byuptocf.u/D5unitsbeforeweexceedthecapacity
constraintonedge.u/.Wealsowishtoallowanalgorithmtoreturnupto11
unitsofflowfromtou,andhencecf.u/D11.
GivenaflownetworkGD.VE/andaflowf,theresidualnetworkofG
inducedbyfisGfD.VEf/,where
EfDfu/2V VWcf.u/>0g: (26.3)
Thatis,aspromisedabove,eachedgeoftheresidualnetwork,orresidualedge,
canadmitaflowthatisgreaterthan0.Figure26.4(a)repeatstheflownetworkG
andflowfofFigure26.1(b),andFigure26.4(b)showsthecorrespondingresidual
networkGf.TheedgesinEfareeitheredgesinEortheirreversals,andthus
jEfj2jEj:
ObservethattheresidualnetworkGfissimilartoaflownetworkwithcapacities
givenbycf.Itdoesnotsatisfyourdefinitionofaflownetworkbecauseitmay
containbothanedge.u/anditsreversal.u/.Otherthanthisdifference,a
residualnetworkhasthesamepropertiesasaflownetwork,andwecandefinea
flowintheresidualnetworkasonethatsatisfiesthedefinitionofaflow,butwith
respecttocapacitiescfinthenetworkGf.
Aflowinaresidualnetworkprovidesaroadmapforaddingflowtotheoriginal
flownetwork.IffisaflowinGandf0isaflowinthecorrespondingresidual
networkGf,wedefinef"f0,theaugmentationofflowfbyf0,tobeafunction
fromV VtoR,definedby
(
f.u/Cf0.u/f0.u/if.u/2E
.f"f0/.u/D (26.4)
0 otherwise:

https://translate.googleusercontent.com/translate_f 85/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Page138

26.2TheFordFulkersonmethod 717

v1 12/12 v3 15/20 v1 12 v3 5
5
11/16 15
11 1 4
S 1/4 4/9 7/7 T S 5 3 7 T
5
8/13 3 4
v2 v4 4/4 8 v2 v4
11/14 11
(un) (segundo)

v1 12/12 v3 19/20 v1 12 v3 1
5
11/16 19
S T S 11 T
1/4 9 7/7 1 1 3 9 7
12/13 3 4
v2 v4 4/4 12 v2 v4
11/14 11
(do) (re)

Figure26.4(a)TheflownetworkGandflowfofFigure26.1(b).(b)TheresidualnetworkGf
withaugmentingpathpshadeditsresidualcapacityiscf.p/Dcf.23/D4.Edgeswith
residualcapacityequalto0,suchas.13/,arenotshown,aconventionwefollowintheremainder
Deestaseccin.(c)TheflowinGthatresultsfromaugmentingalongpathpbyitsresidualcapacity4.
Edgescarryingnoflow,suchas.32/,arelabeledonlybytheircapacity,anotherconventionwe
followthroughout.(d)Theresidualnetworkinducedbytheflowin(c).

Theintuitionbehindthisdefinitionfollowsthedefinitionoftheresidualnetwork.
Weincreasetheflowon.u/byf0.u/butdecreaseitbyf0.u/because
pushingflowonthereverseedgeintheresidualnetworksignifiesdecreasingthe
flowintheoriginalnetwork.Pushingflowonthereverseedgeintheresidual
networkisalsoknownascancellation.Forexample,ifwesend5cratesofhockey
pucksfromutoandsend2cratesfromtou,wecouldequivalently(fromthe
perspectiveofthefinalresult)justsend3createsfromutoandnonefromtou.
Cancellationofthistypeiscrucialforanymaximumflowalgorithm.

Lemma26.1
LetGD.VE/beaflownetworkwithsourcesandsinkt,andletfbeaflow
inG.LetGfbetheresidualnetworkofGinducedbyf,andletf0beaflow
inGf.Thenthefunctionf"f0definedinequation(26.4)isaflowinGwith
valuejf"f0jDjfjCjf0j.

ProofWefirstverifythatf"f0obeysthecapacityconstraintforeachedgeinE
andflowconservationateachvertexinV fstg.

Page139

718 Chapter26MaximumFlow

Forthecapacityconstraint,firstobservethatif.u/2E,thencf.u/D
f.u/.Therefore,wehavef0.u/cf.u/Df.u/,andhence
.f"f0/.u/Df.u/Cf0.u/f0.u/(byequation(26.4))
f.u/Cf0.u/f.u/(becausef0.u/f.u/)
Df0.u/
0:
Enadicin,
.f"f0/.u/
Df.u/Cf0.u/f0.u/(byequation(26.4))
f.u/Cf0.u/ (becauseflowsarenonnegative)
f.u/Ccf.u/ (capacityconstraint)
Df.u/Ccu/f.u/ (definitionofcf)
Dcu/:
Forflowconservation,becausebothfandf0obeyflowconservation,wehave
thatforallu2V fstg,
x x
.f"f0/.u/D .f.u/Cf0.u/f0.u//
2V x 2V x x
re f.u/C f0.u/ f0.u/
https://translate.googleusercontent.com/translate_f 86/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

x2V x2V x2V


re
f.u/C f0.u/ f0.u/
x 2V 2V 2V
re .f.u/Cf0.u/f0.u//
x2V
re .f"f0/.u/
2V
wherethethirdlinefollowsfromthesecondbyflowconservation.
Finally,wecomputethevalueoff"f0.Recallthatwedisallowantiparallel
edgesinG(butnotinGf),andhenceforeachvertex2V,weknowthatthere
canbeanedge.s/or.s/,butneverboth.WedefineV1DfW.s/2Eg
tobethesetofverticeswithedgesfroms,andV2DfW.s/2Egtobethe
setofverticeswithedgestos.WehaveV1[V2Vand,becausewedisallow
antiparalleledges,V
x 1\V2D.Wenowcompute
x
jf"f0jD .f"f0/.s/ .f"f0/.s/
x2V x2V
re .f"f0/.s/ .f"f0/.s/ (26.5)
2V 1 2V 2

Pgina140

26.2TheFordFulkersonmethod 719

wherethesecondlinefollowsbecause.f"f0/.wx/is0if.wx/62E.Wenow
applythedefinitionoff"f0toequation(26.5),andthenreorderandgroupterms
toobtain
jf"f0j
x x
re .f.s/Cf0.s/f0.s// .f.s/Cf0.s/f0.s//
x2V 1
x x 2V 2

re f.s/C f0.s/ f0.s/


2V x1 2V x1 2V x 1

f.s/ f0.s/C f0.s/


x 2V x 2 2V 2 2V 2

re f.s/ f.s/
2V x 2V
1 2
x x x
do f0.sC f0.s/ f0.s/ f0.s/
x 2Vx 1 2V x 2 2V x 12V 2

re f.s/ f.s/C f0.s/ f0.s/: (26.6)


2V 1 2V 2 2V [V 1 2 2V [V 1 2

Inequation(26.6),wecanextendallfoursummationstosumoverV,sinceeach
additionaltermhasvalue0.(Exercise26.21asksyoutoprovethisformally.)We
thushave x x x x
jf"f0jD f.s/ f.s/C f0.s/ f0.s/ (26.7)
2V 2V 2V 2V
DjfjCjf0j:

Augmentingpaths
GivenaflownetworkGD.VE/andaflowf,anaugmentingpathpisa
simplepathfromstotintheresidualnetworkGf.Bythedefinitionoftheresid
ualnetwork,wemayincreasetheflowonanedge.u/ofanaugmentingpath
byuptocf.u/withoutviolatingthecapacityconstraintonwhicheverof.u/
Y.u/isintheoriginalflownetworkG.
TheshadedpathinFigure26.4(b)isanaugmentingpath.Treatingtheresidual
networkGfinthefigureasaflownetwork,wecanincreasetheflowthrougheach
edgeofthispathbyupto4unitswithoutviolatingacapacityconstraint,sincethe
smallestresidualcapacityonthispathiscf.23/D4.Wecallthemaximum
amountbywhichwecanincreasetheflowoneachedgeinanaugmentingpathp
theresidualcapacityofp,givenby
cf.p/Dminfcf.u/W.u/isonpg:

Pgina141

720 Chapter26MaximumFlow

Thefollowinglemma,whoseproofweleaveasExercise26.27,makestheabove
argumentmoreprecise.

https://translate.googleusercontent.com/translate_f 87/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Lemma26.2
LetGD.VE/beaflownetwork,letfbeaflowinG,andletpbeanaugmenting
pathinGf.DefineafunctionfpWV V!Rby
(
cf.p/if.u/isonp
fp.uD (26.8)
0 otherwise:
Then,fpisaflowinGfwithvaluejfpjDcf.p/>0.

Thefollowingcorollaryshowsthatifweaugmentfbyfp,wegetanotherflow
inGwhosevalueisclosertothemaximum.Figure26.4(c)showstheresultof
augmentingtheflowffromFigure26.4(a)bytheflowfpinFigure26.4(b),and
Figure26.4(d)showstheensuingresidualnetwork.

Corollary26.3
LetGD.VE/beaflownetwork,letfbeaflowinG,andletpbean
augmentingpathinGf.Letfpbedefinedasinequation(26.8),andsuppose
thatweaugmentfbyfp.Thenthefunctionf"fpisaflowinGwithvalue
jf"fpjDjfjCjfpj>jfj.

ProofImmediatefromLemmas26.1and26.2.

Cutsofflownetworks
TheFordFulkersonmethodrepeatedlyaugmentstheflowalongaugmentingpaths
untilithasfoundamaximumflow.Howdoweknowthatwhenthealgorithm
terminates,wehaveactuallyfoundamaximumflow?Themaxflowmincuttheo
rem,whichweshallproveshortly,tellsusthataflowismaximumifandonlyifits
residualnetworkcontainsnoaugmentingpath.Toprovethistheorem,though,we
mustfirstexplorethenotionofacutofaflownetwork.
Acut.ST/offlownetworkGD.VE/isapartitionofVintoSand
TDV Ssuchthats2Sandt2T.(Thisdefinitionissimilartothedef
initionofcutthatweusedforminimumspanningtreesinChapter23,except
thatherewearecuttingadirectedgraphratherthananundirectedgraph,andwe
insistthats2Sandt2T.)Iffisaflow,thenthenetflowfST/acrossthe
cut.ST/isdefinedtobe
x x x x
f.ST/D f.u/ f.u/: (26,9)
u2S 2T u2S 2T

Page142

26.2TheFordFulkersonmethod 721

v1 12/12 v3 15/20
11/16
S 1/4 4/9 7/7 T
8/13
v2 v4 4/4
11/14
ST

Figure26.5Acut.ST/intheflownetworkofFigure26.1(b),whereSDfs12gand
TDf34tg.TheverticesinSareblack,andtheverticesinTarewhite.Thenetflow
across.ST/isfST/D19,andthecapacityiscST/D26.

Thecapacityofthecut.ST/is
x x
cST/D cu/: (26.10)
u2S 2T
Aminimumcutofanetworkisacutwhosecapacityisminimumoverallcutsof
lared.
Theasymmetrybetweenthedefinitionsofflowandcapacityofacutisinten
tionalandimportant.Forcapacity,wecountonlythecapacitiesofedgesgoing
fromStoT,ignoringedgesinthereversedirection.Forflow,weconsiderthe
flowgoingfromStoTminustheflowgoinginthereversedirectionfromTtoS.
Thereasonforthisdifferencewillbecomeclearlaterinthissection.
Figure26.5showsthecut.fs12gf34tg/intheflownetworkofFig
ure26.1(b).Thenetflowacrossthiscutis
f.13/Cf.24/f.32/D12C114
D19
andthecapacityofthiscutis
do.13/Cc.24/D12C14

https://translate.googleusercontent.com/translate_f 88/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
D26:
Thefollowinglemmashowsthat,foragivenflowf,thenetflowacrossanycut
isthesame,anditequalsjfj,thevalueoftheflow.

Lemma26.4
LetfbeaflowinaflownetworkGwithsourcesandsinkt,andlet.ST/beany
cutofG.Thenthenetflowacross.ST/isfST/Djfj.

Pgina143

722 Chapter26MaximumFlow

ProofWecanrewritetheflowconservationconditionforanynodeu2VfsTg
como
x x
f.u/ f.u/D0: (26.11)
2V 2V
Takingthedefinitionofjfjfromequation(26.1)andaddingthelefthandsideof
equation(26.11),whichequals0,summedoverallverticesinSfsg,gives
!
x x x x x
jfjD f.s/ f.s/C f.u/ f.u/ :
2V 2V u2Sfsg 2V 2V
Expandingtherighthandsummationandregroupingtermsyields
x x x x x x
jfjD f.s/ f.s/C f.u/ f.u/
2V 2V u2Sfsg
! 2V u2Sfsg 2V !
x x x x
re f.s/C f.u/ f.s/C f.u/
2V
x x u2Sfsg
x x 2V u2Sfsg
re f.u/ f.u/:
2Vu2S 2Vu2S
BecauseVDS[TandS\TD,wecanspliteachsummationoverVinto
summationsoverSandTtoobtain
x x x x x x x x
jfjD f.u/C f.u/ f.u/ f.u/
x2S xu2S x2Txu2S 2S u2S 2T u2S
re f.u/ f.u/
2T u2S 2T u2S !
x x x x
do f.u/ f.u/ :
2S u2S 2S u2S
Thetwosummationswithintheparenthesesareactuallythesame,sinceforall
verticesxy2V,thetermfxy/appearsonceineachsummation.Hence,these
summationscancel,andwehave
x x x x
jfjD f.u/ f.u/
u2S 2T u2S 2T
Df.ST/:

AcorollarytoLemma26.4showshowwecanusecutcapacitiestoboundthe
valueofaflow.

Page144

26.2TheFordFulkersonmethod 723

Corollary26.5
ThevalueofanyflowfinaflownetworkGisboundedfromabovebythecapacity
ofanycutofG.

ProofLet.ST/beanycutofGandletfbeanyflow.ByLemma26.4andthe
capacityconstraint,
jfjDf.ST/
x x x x
re f.u/ f.u/
u2S
x x 2T u2S 2T
UN f.u/
xu2S x2T
UN cu/

https://translate.googleusercontent.com/translate_f 89/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
u2S 2T
DcST/:

Corollary26.5yieldstheimmediateconsequencethatthevalueofamaximum
flowinanetworkisboundedfromabovebythecapacityofaminimumcutof
lared.Theimportantmaxflowmincuttheorem,whichwenowstateand
prove,saysthatthevalueofamaximumflowisinfactequaltothecapacityofa
minimumcut.

Theorem26.6(Maxflowmincuttheorem)
IffisaflowinaflownetworkGD.VE/withsourcesandsinkt,thenthe
followingconditionsareequivalent:
1.fisamaximumflowinG.
2.TheresidualnetworkGfcontainsnoaugmentingpaths.
3.jfjDcST/forsomecut.ST/ofG.

Proof.1/).2/:Supposeforthesakeofcontradictionthatfisamaximum
flowinGbutthatGfhasanaugmentingpathp.Then,byCorollary26.3,the
flowfoundbyaugmentingfbyfp,wherefpisgivenbyequation(26.8),isaflow
inGwithvaluestrictlygreaterthanjfj,contradictingtheassumptionthatfisa
maximumflow.
.2/).3/:SupposethatGfhasnoaugmentingpath,thatis,thatGfcontains
nopathfromstot.Define
SDf2VWthereexistsapathfromstoinGfg
andTDV S.Thepartition.ST/isacut:wehaves2Striviallyandt62S
becausethereisnopathfromstotinGf.Nowconsiderapairofvertices

Pgina145

724 Chapter26MaximumFlow

u2Sand 2T.If.u/2E,wemusthavef.u/Dcu/,since
otherwise.u/2Ef,whichwouldplaceinsetS.If.u/2E,wemust
havef.u/D0,becauseotherwisecf.u/Df.u/wouldbepositiveand
wewouldhave.u/2Ef,whichwouldplaceinS.Ofcourse,ifneither.u/
nor.u/isinE,thenf.u/Df.u/D0.Wethushave
x x x x
f.ST/D f.u/ f.u/
xu2S x2T x 2Txu2S
re cu/ 0
u2S 2T 2T u2S
DcST/:
ByLemma26.4,therefore,jfjDfST/DcST/.
.3/).1/:ByCorollary26.5,jfjcST/forallcuts.ST/.Thecondition
jfjDcST/thusimpliesthatfisamaximumflow.

ThebasicFordFulkersonalgorithm
IneachiterationoftheFordFulkersonmethod,wefindsomeaugmentingpathp
anduseptomodifytheflowf.AsLemma26.2andCorollary26.3suggest,we
replacefbyf"fp,obtaininganewflowwhosevalueisjfjCjfpj.Thefollow
ingimplementationofthemethodcomputesthemaximumflowinaflownetwork
GD.VE/byupdatingtheflowattribute.u/:fforeachedge.u/2E.1
If.u/62E,weassumeimplicitlythat.u/:fD0.Wealsoassumethatwe
aregiventhecapacitiescu/alongwiththeflownetwork,andcu/D0
if.u/62E.Wecomputetheresidualcapacitycf.u/inaccordancewiththe
formula(26.2).Theexpressioncf.p/inthecodeisjustatemporaryvariablethat
storestheresidualcapacityofthepathp.

FORDFULKERSON.Gst/
1foreachedge.u/2G:E
2 .u/:fD0
3whilethereexistsapathpfromstotintheresidualnetworkGf
4 cf.p/Dminfcf.u/W.u/isinpg
5 foreachedge.u/inp
6 if.u/2E
7 .u/:fD.u/:fCcf.p/
8 else.u/:fD.u/:f cf.p/

1RecallfromSection22.1thatwerepresentanattributefforedge.u/withthesamestyleof
notation.u/:fthatweuseforanattributeofanyotherobject.

https://translate.googleusercontent.com/translate_f 90/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Page146

26.2TheFordFulkersonmethod 725

TheFORDFULKERSONalgorithmsimplyexpandsontheFORDFULKERSON
METHODpseudocodegivenearlier.Figure26.6showstheresultofeachiteration
inasamplerun.Lines12initializetheflowfto0.Thewhileloopoflines38
repeatedlyfindsanaugmentingpathpinGfandaugmentsflowfalongpby
theresidualcapacitycf.p/.Eachresidualedgeinpathpiseitheranedgeinthe
originalnetworkorthereversalofanedgeintheoriginalnetwork.Lines68
updatetheflowineachcaseappropriately,addingflowwhentheresidualedgeis
anoriginaledgeandsubtractingitotherwise.Whennoaugmentingpathsexist,the
flowfisamaximumflow.

AnalysisofFordFulkerson
TherunningtimeofFORDFULKERSONdependsonhowwefindtheaugmenting
pathpinline3.Ifwechooseitpoorly,thealgorithmmightnoteventerminate:the
valueoftheflowwillincreasewithsuccessiveaugmentations,butitneednoteven
convergetothemaximumflowvalue.2Ifwefindtheaugmentingpathbyusinga
breadthfirstsearch(whichwesawinSection22.2),however,thealgorithmrunsin
polynomialtime.Beforeprovingthisresult,weobtainasimpleboundforthecase
inwhichwechoosetheaugmentingpatharbitrarilyandallcapacitiesareintegers.
Inpractice,themaximumflowproblemoftenariseswithintegralcapacities.Si
thecapacitiesarerationalnumbers,wecanapplyanappropriatescalingtransfor
mationtomakethemallintegral.Iffdenotesamaximumflowinthetransformed
network,thenastraightforwardimplementationofFORDFULKERSONexecutes
thewhileloopoflines38atmostjfjtimes,sincetheflowvalueincreasesbyat
leastoneunitineachiteration.
Wecanperformtheworkdonewithinthewhileloopefficientlyifweimplement
theflownetworkGD.VE/withtherightdatastructureandfindanaugmenting
pathbyalineartimealgorithm.Letusassumethatwekeepadatastructurecor
respondingtoadirectedgraphG0D.VE0/,whereE0Dfu/W.u/2Eor
.u/2Eg.EdgesinthenetworkGarealsoedgesinG0,andthereforewecan
easilymaintaincapacitiesandflowsinthisdatastructure.GivenaflowfonG,
theedgesintheresidualnetworkGfconsistofalledges.u/ofG0suchthat
cf.u/>0,wherecfconformstoequation(26.2).Thetimetofindapathin
aresidualnetworkisthereforeOVCE0/DOE/ifweuseeitherdepthfirst
searchorbreadthfirstsearch.EachiterationofthewhileloopthustakesOE/
time,asdoestheinitializationinlines12,makingthetotalrunningtimeofthe
FORDFULKERSONalgorithmOEjfj/.

2TheFordFulkersonmethodmightfailtoterminateonlyifedgecapacitiesareirrationalnumbers.

Pgina147

726 Chapter26MaximumFlow

v1 12 v3 v1 4/12 v3
diecisis 20 20
4/16
(un) S 4 7 T S 4 7 T
9 4/9
13 4 13 4/4
v2 v4 v2 v4
14 4/14
8 8/12
v1 v3 v1 v3 4/20
12 4 20
4/16
4
(segundo)
S 4 4 5 7 T S 4/4 4/9 7 T
13 10 4 4/13
v2 v4 v2 v4 4/4
4 4/14

v1 4 v3 v1 8/12 v3
12 diecisis 8/20
8 8/16
4 4 4
(do) S 9 4 7 T S 4 9 7 T
5
4 10 4 4/13
v2 v4 v2 v4 4/4
4 4/14

Figure26.6TheexecutionofthebasicFordFulkersonalgorithm.(a)(e)Successiveiterationsof
thewhileloop.TheleftsideofeachpartshowstheresidualnetworkGffromline3withashaded
augmentingpathp.Therightsideofeachpartshowsthenewflowfthatresultsfromaugmentingf

https://translate.googleusercontent.com/translate_f 91/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
byfp.Theresidualnetworkin(a)istheinputnetworkG.
Whenthecapacitiesareintegralandtheoptimalflowvaluejfjissmall,the
runningtimeoftheFordFulkersonalgorithmisgood.Figure26.7(a)showsanex
ampleofwhatcanhappenonasimpleflownetworkforwhichjfjislarge.Amax
imumflowinthisnetworkhasvalue2,000,000:1,000,000unitsofflowtraverse
thepaths!u!t,andanother1,000,000unitstraversethepaths!!t.Si
thefirstaugmentingpathfoundbyFORDFULKERSONiss!u!!t,shown
inFigure26.7(a),theflowhasvalue1afterthefirstiteration.Theresultingresid
ualnetworkappearsinFigure26.7(b).Iftheseconditerationfindstheaugment
ingpaths!!u!t,asshowninFigure26.7(b),theflowthenhasvalue2.
Figure26.7(c)showstheresultingresidualnetwork.Wecancontinue,choosing
theaugmentingpaths!u!!tintheoddnumberediterationsandtheaug
mentingpaths!!u!tintheevennumberediterations.Wewouldperform
atotalof2,000,000augmentations,increasingtheflowvaluebyonly1unitineach.

Pgina148

26.2TheFordFulkersonmethod 727

4 8/12
v1 v3 12 v1 v3 15/20
8 8 8/16
8 8
(re) S 4 9 7 T S 4 9 7/7 T
9
4 10 4 11/13
v2 v4 v2 v4 4/4
4 11/14
4 12/12 v3
v1 v3 5 v1 19/20
8 8
15 12/16
(mi) S 8 4 T 4
11 9 7 S 9 7/7 T
2 3 11/13
v2 v4 4 4/4
v2 v4
11 11/14

v1 12 v3
4 1
12 19
(f) S 4 9 7 T
11
2 3 4
v2 v4
11

Figure26.6,continued(f)Theresidualnetworkatthelastwhilelooptest.Ithasnoaugmenting
paths,andtheflowfshownin(e)isthereforeamaximumflow.Thevalueofthemaximumflow
foundis23.

TheEdmondsKarpalgorithm
WecanimprovetheboundonFORDFULKERSONbyfindingtheaugmenting
pathpinline3withabreadthfirstsearch.Thatis,wechoosetheaugmenting
pathasashortestpathfromstotintheresidualnetwork,whereeachedgehas
unitdistance(weight).WecalltheFordFulkersonmethodsoimplementedthe
EdmondsKarpalgorithm.WenowprovethattheEdmondsKarpalgorithmruns
inO.VE2/time.
TheanalysisdependsonthedistancestoverticesintheresidualnetworkGf.
Thefollowinglemmausesthenotationf.u/fortheshortestpathdistance
fromutoinGf,whereeachedgehasunitdistance.

Lemma26.7
IftheEdmondsKarpalgorithmisrunonaflownetworkGD.VE/withsources
andsinkt,thenforallvertices2V fstg,theshortestpathdistancef.s/
intheresidualnetworkGfincreasesmonotonicallywitheachflowaugmentation.

Pgina149

728 Chapter26MaximumFlow

Usted
1,000,000 Usted
1,000,000 Usted
999,999
1,000,000 999,999 999,999
1 1 1 1 11
S T S T S 999,999 T
1,000,000 1,000,000 999,999 999,999
V 1,000,000 V 1 1 V 1

https://translate.googleusercontent.com/translate_f 92/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

(un) (segundo) (do)

Figure26.7(a)AflownetworkforwhichFORDFULKERSONcantake.Ejfj/time,
wherefisamaximumflow,shownherewithjfjD2,000,000.Theshadedpathisanaug
mentingpathwithresidualcapacity1.(b)Theresultingresidualnetwork,withanotheraugmenting
pathwhoseresidualcapacityis1.(c)Theresultingresidualnetwork.

ProofWewillsupposethatforsomevertex2V fstg,thereisaflowaug
mentationthatcausestheshortestpathdistancefromstotodecrease,andthen
wewillderiveacontradiction.Letfbetheflowjustbeforethefirstaugmentation
thatdecreasessomeshortestpathdistance,andletf0betheflowjustafterward.
Letbethevertexwiththeminimumf .s/whosedistancewasdecreasedby
0

theaugmentation,sothatf .s/<f.s/.LetpDsu!beashortest
0

pathfromstoinGf ,sothat.u/2Ef and


0 0

f .su/Df .s/1:
0 0 (26.12)
Becauseofhowwechose,weknowthatthedistanceofvertexufromthesources
didnotdecrease,ie,
f .su/
0 f.su/: (26,13)
Weclaimthat.u/62Ef.Porqu?Ifwehad.u/2Ef,thenwewouldalsohave
f.s/f.su/C1(byLemma24.10,thetriangleinequality)
f .su/C1(byinequality(26.13))
0

Df .s/
0 (byequation(26.12)),
whichcontradictsourassumptionthatf .s/<f.s/.
0

Howcanwehave.u/62Efand.u/2Ef ?Theaugmentationmust
0

haveincreasedtheflowfromtou.TheEdmondsKarpalgorithmalwaysaug
mentsflowalongshortestpaths,andthereforetheshortestpathfromstouinGf
has.u/asitslastedge.Porlotanto,
f.s/Df.su/1
f .su/1(byinequality(26.13))
0

Df .s/2(byequation(26.12)),
0

Pgina150

26.2TheFordFulkersonmethod 729

whichcontradictsourassumptionthatf .s/<f.s/.Weconcludethatour
0

assumptionthatsuchavertexexistsisincorrect.

ThenexttheoremboundsthenumberofiterationsoftheEdmondsKarpalgo
rithm.

Theorem26.8
IftheEdmondsKarpalgorithmisrunonaflownetworkGD.VE/withsources
andsinkt,thenthetotalnumberofflowaugmentationsperformedbythealgorithm
isO.VE/.

ProofWesaythatanedge.u/inaresidualnetworkGfiscriticalonanaug
mentingpathpiftheresidualcapacityofpistheresidualcapacityof.u/,that
is,ifcf.p/Dcf.u/.Afterwehaveaugmentedflowalonganaugmentingpath,
anycriticaledgeonthepathdisappearsfromtheresidualnetwork.Moreover,at
leastoneedgeonanyaugmentingpathmustbecritical.Wewillshowthateachof
thejEjedgescanbecomecriticalatmostjVj=2times.
LetuandbeverticesinVthatareconnectedbyanedgeinE.Sinceaugment
ingpathsareshortestpaths,when.u/iscriticalforthefirsttime,wehave
f.s/Df.su/C1:
Oncetheflowisaugmented,theedge.u/disappearsfromtheresidualnetwork.
Itcannotreappearlateronanotheraugmentingpathuntilaftertheflowfromuto
isdecreased,whichoccursonlyif.u/appearsonanaugmentingpath.Iff0is
theflowinGwhenthiseventoccurs,thenwehave
f .su/Df .s/C1:
0 0

Sincef.s/f .s/byLemma26.7,wehave
0

f .su/Df .s/C1
0 0

f.s/C1
Df.su/C2:
Consequently,fromthetime.u/becomescriticaltothetimewhenitnext
becomescritical,thedistanceofufromthesourceincreasesbyatleast2.The
distanceofufromthesourceisinitiallyatleast0.Theintermediateverticesona
shortestpathfromstoucannotcontains,u,ort(since.u/onanaugmenting

https://translate.googleusercontent.com/translate_f 93/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
pathimpliesthatut).Therefore,untilubecomesunreachablefromthesource,
ifever,itsdistanceisatmostjVj2.Thus,afterthefirsttimethat.u/becomes
critical,itcanbecomecriticalatmost.jVj2/=2DjVj=21timesmore,fora
totalofatmostjVj=2times.SincethereareOE/pairsofverticesthatcanhavean
edgebetweentheminaresidualnetwork,thetotalnumberofcriticaledgesduring

Pgina151

730 Chapter26MaximumFlow

theentireexecutionoftheEdmondsKarpalgorithmisO.VE/.Eachaugmenting
pathhasatleastonecriticaledge,andhencethetheoremfollows.

BecausewecanimplementeachiterationofFORDFULKERSONinOE/time
whenwefindtheaugmentingpathbybreadthfirstsearch,thetotalrunningtimeof
theEdmondsKarpalgorithmisO.VE2/.Weshallseethatpushrelabelalgorithms
canyieldevenbetterbounds.ThealgorithmofSection26.4givesamethodfor
achievinganOV2E/runningtime,whichformsthebasisfortheOV3/time
algorithmofSection26.5.

Exercises

26.21
Provethatthesummationsinequation(26.6)equalthesummationsinequa
tion(26.7).

26.22
InFigure26.1(b),whatistheflowacrossthecut.fs24gf13tg/?Quees
thecapacityofthiscut?

26.23
ShowtheexecutionoftheEdmondsKarpalgorithmontheflownetworkofFig
ure26.1(a).

26.24
IntheexampleofFigure26.6,whatistheminimumcutcorrespondingtothemax
imumflowshown?Oftheaugmentingpathsappearingintheexample,whichone
cancelsflow?

26.25
RecallthattheconstructioninSection26.1thatconvertsaflownetworkwithmul
tiplesourcesandsinksintoasinglesource,singlesinknetworkaddsedgeswith
infinitecapacity.Provethatanyflowintheresultingnetworkhasafinitevalue
iftheedgesoftheoriginalnetworkwithmultiplesourcesandsinkshavefinite
capacidad.

26.26
Supposethateachsourcesiinaflownetworkwithmultiplesourcesandsinks
PAG
producesexactlypiunitsofflow,sothat 2Vf.sPAG
i/Dpi.Supposealso
thateachsinkt
PAG PAG jconsumesexactlyqjunits,sothat 2Vf. tj/Dqj,where
ipiD jqj.Showhowtoconverttheproblemoffindingaflowfthatobeys

Pgina152

26.2TheFordFulkersonmethod 731

theseadditionalconstraintsintotheproblemoffindingamaximumflowinasingle
source,singlesinkflownetwork.

26.27
ProveLemma26.2.

26.28
Supposethatweredefinetheresidualnetworktodisallowedgesintos.Arguethat
theprocedureFORDFULKERSONstillcorrectlycomputesamaximumflow.

26.29
Supposethatbothfandf0areflowsinanetworkGandwecomputeflowf"f0.
Doestheaugmentedflowsatisfytheflowconservationproperty?Doesitsatisfy
thecapacityconstraint?

26.210
ShowhowtofindamaximumflowinanetworkGD.VE/byasequenceofat
mostjEjaugmentingpaths.(Hint:Determinethepathsafterfindingthemaximum
https://translate.googleusercontent.com/translate_f 94/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
flow.)

26.211
Theedgeconnectivityofanundirectedgraphistheminimumnumberkofedges
thatmustberemovedtodisconnectthegraph.Forexample,theedgeconnectivity
ofatreeis1,andtheedgeconnectivityofacyclicchainofverticesis2.Show
howtodeterminetheedgeconnectivityofanundirectedgraphGD.VE/by
runningamaximumflowalgorithmonatmostjVjflownetworks,eachhaving
OV/verticesandOE/edges.

26.212
SupposethatyouaregivenaflownetworkG,andGhasedgesenteringthe
sources.LetfbeaflowinGinwhichoneoftheedges.s/enteringthesource
hasf.s/D1.Provethattheremustexistanotherflowf0withf0.s/D0
suchthatjfjDjf0j.GiveanOE/timealgorithmtocomputef0,givenf,and
assumingthatalledgecapacitiesareintegers.

26.213
Supposethatyouwishtofind,amongallminimumcutsinaflownetworkGwith
integralcapacities,onethatcontainsthesmallestnumberofedges.Showhowto
modifythecapacitiesofGtocreateanewflownetworkG0inwhichanyminimum
cutinG0isaminimumcutwiththesmallestnumberofedgesinG.

Pgina153

732 Chapter26MaximumFlow

26.3Maximumbipartitematching

Somecombinatorialproblemscaneasilybecastasmaximumflowproblems.los
multiplesource,multiplesinkmaximumflowproblemfromSection26.1gaveus
oneexample.Someothercombinatorialproblemsseemonthesurfacetohavelittle
todowithflownetworks,butcaninfactbereducedtomaximumflowproblems.
Thissectionpresentsonesuchproblem:findingamaximummatchinginabipartite
grafico.Inordertosolvethisproblem,weshalltakeadvantageofanintegrality
propertyprovidedbytheFordFulkersonmethod.Weshallalsoseehowtouse
theFordFulkersonmethodtosolvethemaximumbipartitematchingproblemon
agraphGD.VE/inO.VE/time.

Themaximumbipartitematchingproblem
GivenanundirectedgraphGD.VE/,amatchingisasubsetofedgesME
suchthatforallvertices 2V,atmostoneedgeofMisincidenton.Nosotros
saythatavertex 2VismatchedbythematchingMifsomeedgeinMis
incidentonotherwise,isunmatched.Amaximummatchingisamatching
ofmaximumcardinality,thatis,amatchingMsuchthatforanymatchingM0,
wehavejMjjM0j.Inthissection,weshallrestrictourattentiontofinding
maximummatchingsinbipartitegraphs:graphsinwhichthevertexsetcanbe
partitionedintoVDL[R,whereLandRaredisjointandalledgesinE
gobetweenLandR.WefurtherassumethateveryvertexinVhasatleastone
incidentedge.Figure26.8illustratesthenotionofamatchinginabipartitegraph.
Theproblemoffindingamaximummatchinginabipartitegraphhasmany
practicalapplications.Asanexample,wemightconsidermatchingasetLofma
chineswithasetRoftaskstobeperformedsimultaneously.Wetakethepresence
ofedge.u/inEtomeanthataparticularmachineu2Liscapableofper
formingaparticulartask2R.Amaximummatchingprovidesworkforasmany
machinesaspossible.

Findingamaximumbipartitematching
WecanusetheFordFulkersonmethodtofindamaximummatchinginanundi
rectedbipartitegraphGD.VE/intimepolynomialinjVjandjEj.Thetrickis
toconstructaflownetworkinwhichflowscorrespondtomatchings,asshownin
Figure26.8(c).WedefinethecorrespondingflownetworkG0D.V0E0/forthe
bipartitegraphGasfollows.Weletthesourcesandsinktbenewverticesnot
inV,andweletV0DV[fstg.IfthevertexpartitionofGisVDL[R,the

Pgina154

https://translate.googleusercontent.com/translate_f 95/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
26.3Maximumbipartitematching 733

S T

L R L R L R
(un) (segundo) (do)

Figure26.8AbipartitegraphGD.VE/withvertexpartitionVDL[R.(a)Amatching
withcardinality2,indicatedbyshadededges.(b)Amaximummatchingwithcardinality3.(c)The
correspondingflownetworkG0withamaximumflowshown.Eachedgehasunitcapacity.Shaded
edgeshaveaflowof1,andallotheredgescarrynoflow.TheshadededgesfromLtoRcorrespond
tothoseinthemaximummatchingfrom(b).

directededgesofG0aretheedgesofE,directedfromLtoR,alongwithjVjnew
directededges:
E0Dfsu/Wu2Lg[fu/W.u/2Eg[f.t/W2Rg:
Tocompletetheconstruction,weassignunitcapacitytoeachedgeinE0.Desde
eachvertexinVhasatleastoneincidentedge,jEjjVj=2.Thus,jEjjE0jD
jEjCjVj3jEj,andsojE0jD.E/.
ThefollowinglemmashowsthatamatchinginGcorrespondsdirectlytoaflow
inG'scorrespondingflownetworkG0.Wesaythataflowfonaflownetwork
GD.VE/isintegervaluediff.u/isanintegerforall.u/2V V.

Lemma26.9
LetGD.VE/beabipartitegraphwithvertexpartitionVDL[R,andlet
G0D.V0E0/beitscorrespondingflownetwork.IfMisamatchinginG,then
thereisanintegervaluedflowfinG0withvaluejfjDjMj.Conversely,iff
isanintegervaluedflowinG0,thenthereisamatchingMinGwithcardinality
jMjDjfj.

ProofWefirstshowthatamatchingMinGcorrespondstoanintegervalued
flowfinG0.Definefasfollows.If.u/2M,thenf.su/Df.uD
F.t/D1.Forallotheredges.u/2E0,wedefinef.u/D0.Itissimple
toverifythatfsatisfiesthecapacityconstraintandflowconservation.

Pgina155

734 Chapter26MaximumFlow

Intuitively,eachedge.u/2McorrespondstooneunitofflowinG0that
traversesthepaths!u!!t.Moreover,thepathsinducedbyedgesinM
arevertexdisjoint,exceptforsandt.Thenetflowacrosscut.L[fsgR[ftg/
isequaltojMjthus,byLemma26.4,thevalueoftheflowisjfjDjMj.
Toprovetheconverse,letfbeanintegervaluedflowinG0,andlet
MDfu/Wu2L2Randf.u/>0g:
Eachvertexu2Lhasonlyoneenteringedge,namely.su/,anditscapacity
is1.Thus,eachu2Lhasatmostoneunitofflowenteringit,andifoneunitof
flowdoesenter,byflowconservation,oneunitofflowmustleave.Furthermore,
sincefisintegervalued,foreachu2L,theoneunitofflowcanenteronatmost
oneedgeandcanleaveonatmostoneedge.Thus,oneunitofflowentersuifand
onlyifthereisexactlyonevertex2Rsuchthatf.u/D1,andatmostone
edgeleavingeachu2Lcarriespositiveflow.Asymmetricargumentappliesto
each2R.ThesetMisthereforeamatching.
ToseethatjMjDjfj,observethatforeverymatchedvertexu2L,wehave
f.su/D1,andforeveryedge.u/2E M,wehavef.u/D0.Conse
quently,f.L[fsgR[ftg/,thenetflowacrosscut.L[fsgR[ftg/,isequal
tojMj.ApplyingLemma26.4,wehavethatjfjDf.L[fsgR[ftg/DjMj.

BasedonLemma26.9,wewouldliketoconcludethatamaximummatching
inabipartitegraphGcorrespondstoamaximumflowinitscorrespondingflow
networkG0,andwecanthereforecomputeamaximummatchinginGbyrunning
amaximumflowalgorithmonG0.Theonlyhitchinthisreasoningisthatthe
maximumflowalgorithmmightreturnaflowinG0forwhichsomef.u/is
notaninteger,eventhoughtheflowvaluejfjmustbeaninteger.Thefollowing
theoremshowsthatifweusetheFordFulkersonmethod,thisdifficultycannot
surgir.
https://translate.googleusercontent.com/translate_f 96/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Theorem26.10(Integralitytheorem)
Ifthecapacityfunctionctakesononlyintegralvalues,thenthemaximumflowf
producedbytheFordFulkersonmethodhasthepropertythatjfjisaninteger.
Moreover,forallverticesuand,thevalueoff.u/isaninteger.

ProofTheproofisbyinductiononthenumberofiterations.Weleaveitas
Exercise26.32.

WecannowprovethefollowingcorollarytoLemma26.9.

Pgina156

26.3Maximumbipartitematching 735.

Corollary26.11
ThecardinalityofamaximummatchingMinabipartitegraphGequalsthevalue
ofamaximumflowfinitscorrespondingflownetworkG0.

ProofWeusethenomenclaturefromLemma26.9.SupposethatMisamax
imummatchinginGandthatthecorrespondingflowfinG0isnotmaximum.
Thenthereisamaximumflowf0inG0suchthatjf0j>jfj.Sincetheca
pacitiesinG0areintegervalued,byTheorem26.10,wecanassumethatf0is
integervalued.Thus,f0correspondstoamatchingM0inGwithcardinality
jM0jDjf0j>jfjDjMj,contradictingourassumptionthatMisamaximum
pareo.Inasimilarmanner,wecanshowthatiffisamaximumflowinG0,its
correspondingmatchingisamaximummatchingonG.

Thus,givenabipartiteundirectedgraphG,wecanfindamaximummatchingby
creatingtheflownetworkG0,runningtheFordFulkersonmethod,anddirectlyob
tainingamaximummatchingMfromtheintegervaluedmaximumflowffound.
Sinceanymatchinginabipartitegraphhascardinalityatmostmin.LR/DOV/,
thevalueofthemaximumflowinG0isOV/.Wecanthereforefindamaximum
matchinginabipartitegraphintimeO.VE0/DO.VE/,sincejE0jD.E/.

Exercises

26.31
RuntheFordFulkersonalgorithmontheflownetworkinFigure26.8(c)andshow
theresidualnetworkaftereachflowaugmentation.NumbertheverticesinLtop
tobottomfrom1to5andinRtoptobottomfrom6to9.Foreachiteration,pick
theaugmentingpaththatislexicographicallysmallest.

26.32
ProveTheorem26.10.

26.33
LetGD.VE/beabipartitegraphwithvertexpartitionVDL[R,andletG0
beitscorrespondingflownetwork.Giveagoodupperboundonthelengthofany
augmentingpathfoundinG0duringtheexecutionofFORDFULKERSON.

26.34?
Aperfectmatchingisamatchinginwhicheveryvertexismatched.LetGD
.VE/beanundirectedbipartitegraphwithvertexpartitionVDL[R,where
jLjDjRj.ForanyXV,definetheneighborhoodofXas

NX/Dfy2VW.xy/2Eforsomex2Xg

Pgina157

736 Chapter26MaximumFlow

thatis,thesetofverticesadjacenttosomememberofX.ProveHall'stheorem:
thereexistsaperfectmatchinginGifandonlyifjAjjN.A/jforeverysubset
AL.

26.35?
WesaythatabipartitegraphGD.VE/,whereVDL[R,isdregularifevery
vertex2Vhasdegreeexactlyd.EverydregularbipartitegraphhasjLjDjRj.
ProvethateverydregularbipartitegraphhasamatchingofcardinalityjLjby
arguingthataminimumcutofthecorrespondingflownetworkhascapacityjLj.

https://translate.googleusercontent.com/translate_f 97/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

?26.4Pushrelabelalgorithms

Inthissection,wepresentthepushrelabelapproachtocomputingmaximum
flows.Todate,manyoftheasymptoticallyfastestmaximumflowalgorithmsare
pushrelabelalgorithms,andthefastestactualimplementationsofmaximumflow
algorithmsarebasedonthepushrelabelmethod.Pushrelabelmethodsalsoeffi
cientlysolveotherflowproblems,suchastheminimumcostflowproblem.Esta
sectionintroducesGoldberg'sgenericmaximumflowalgorithm,whichhasa
simpleimplementationthatrunsinOV2E/time,therebyimprovinguponthe
O.VE2/boundoftheEdmondsKarpalgorithm.Section26.5refinesthegeneric
algorithmtoobtainanotherpushrelabelalgorithmthatrunsinOV3/time.
PushrelabelalgorithmsworkinamorelocalizedmannerthantheFord
Fulkersonmethod.Ratherthanexaminetheentireresidualnetworktofindanaug
mentingpath,pushrelabelalgorithmsworkononevertexatatime,lookingonly
atthevertex'sneighborsintheresidualnetwork.Furthermore,unliketheFord
Fulkersonmethod,pushrelabelalgorithmsdonotmaintaintheflowconservation
propertythroughouttheirexecution.Theydo,however,maintainapreflow,which
isafunctionfWVV!Rthatsatisfiesthecapacityconstraintandthefollowing
relaxationofflowconservation:
x x
f.u/ f.u/ 0
2V 2V
forallverticesu2V fsg.Thatis,theflowintoavertexmayexceedtheflow
fuera.Wecallthequantity
x x
eu/D f.u/ f.u/ (26.14)
2V 2V
theexcessflowintovertexu.Theexcessatavertexistheamountbywhichthe
flowinexceedstheflowout.Wesaythatavertexu2V fstgisoverflowingif
eu/>0.

Pgina158

26.4Pushrelabelalgorithms 737

Weshallbeginthissectionbydescribingtheintuitionbehindthepushrelabel
Mtodo.Weshalltheninvestigatethetwooperationsemployedbythemethod:
pushingpreflowandrelabelingavertex.Finally,weshallpresentageneric
pushrelabelalgorithmandanalyzeitscorrectnessandrunningtime.

Intuicin

Youcanunderstandtheintuitionbehindthepushrelabelmethodintermsoffluid
flows:weconsideraflownetworkGD.VE/tobeasystemofinterconnected
pipesofgivencapacities.ApplyingthisanalogytotheFordFulkersonmethod,
wemightsaythateachaugmentingpathinthenetworkgivesrisetoanadditional
streamoffluid,withnobranchpoints,flowingfromthesourcetothesink.los
FordFulkersonmethoditerativelyaddsmorestreamsofflowuntilnomorecanbe
adicional.
Thegenericpushrelabelalgorithmhasaratherdifferentintuition.Asbefore,
directededgescorrespondtopipes.Vertices,whicharepipejunctions,havetwo
interestingproperties.First,toaccommodateexcessflow,eachvertexhasanout
flowpipeleadingtoanarbitrarilylargereservoirthatcanaccumulatefluid.Second,
eachvertex,itsreservoir,andallitspipeconnectionssitonaplatformwhoseheight
increasesasthealgorithmprogresses.
Vertexheightsdeterminehowflowispushed:wepushflowonlydownhill,that
is,fromahighervertextoalowervertex.Theflowfromalowervertextoahigher
vertexmaybepositive,butoperationsthatpushflowpushitonlydownhill.Nosotros
fixtheheightofthesourceatjVjandtheheightofthesinkat0.Allothervertex
heightsstartat0andincreasewithtime.Thealgorithmfirstsendsasmuchflowas
possibledownhillfromthesourcetowardthesink.Theamountitsendsisexactly
enoughtofilleachoutgoingpipefromthesourcetocapacitythatis,itsendsthe
capacityofthecut.sV fsg/.Whenflowfirstentersanintermediatevertex,it
collectsinthevertex'sreservoir.Fromthere,weeventuallypushitdownhill.
Wemayeventuallyfindthattheonlypipesthatleaveavertexuandarenot
alreadysaturatedwithflowconnecttoverticesthatareonthesamelevelasuor
areuphillfromu.Inthiscase,toridanoverflowingvertexuofitsexcessflow,we
mustincreaseitsheightanoperationcalledrelabelingvertexu.Weincrease
itsheighttooneunitmorethantheheightofthelowestofitsneighborstowhich
ithasanunsaturatedpipe.Afteravertexisrelabeled,therefore,ithasatleastone
outgoingpipethroughwhichwecanpushmoreflow.
Eventually,alltheflowthatcanpossiblygetthroughtothesinkhasarrivedthere.
Nomorecanarrive,becausethepipesobeythecapacityconstraintstheamountof
flowacrossanycutisstilllimitedbythecapacityofthecut.Tomakethepreflow
alegalflow,thealgorithmthensendstheexcesscollectedinthereservoirsof
https://translate.googleusercontent.com/translate_f 98/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
overflowingverticesbacktothesourcebycontinuingtorelabelverticestoabove

Pgina159

738 Chapter26MaximumFlow

thefixedheightjVjofthesource.Asweshallsee,oncewehaveemptiedallthe
reservoirs,thepreflowisnotonlyalegalflow,itisalsoamaximumflow.

Thebasicoperations
Fromtheprecedingdiscussion,weseethatapushrelabelalgorithmperformstwo
basicoperations:pushingflowexcessfromavertextooneofitsneighborsand
relabelingavertex.Thesituationsinwhichtheseoperationsapplydependonthe
heightsofvertices,whichwenowdefineprecisely.
LetGD.VE/beaflownetworkwithsourcesandsinkt,andletfbea
preflowinG.AfunctionhWV!Nisaheightfunction3ifhs/DjVj,
ht/D0,and
hu/h./C1
foreveryresidualedge.u/2Ef.Weimmediatelyobtainthefollowinglemma.

Lemma26.12
LetGD.VE/beaflownetwork,letfbeapreflowinG,andlethbeaheight
functiononV.Foranytwoverticesu2V,ifhu/>h./C1,then.u/is
notanedgeintheresidualnetwork.

Thepushoperation
ThebasicoperationPUSH.u/appliesifuisanoverflowingvertex,cf.u/>0,
andhu/Dh./C1.Thepseudocodebelowupdatesthepreflowfandtheexcess
flowsforuand.Itassumesthatwecancomputeresidualcapacitycf.u/in
constanttimegivencandf.Wemaintaintheexcessflowstoredatavertexuas
theattributeu:eandtheheightofuastheattributeu:h.Theexpressionf.u/
isatemporaryvariablethatstorestheamountofflowthatwecanpushfromuto.

3Intheliterature,aheightfunctionistypicallycalledadistancefunction,andtheheightofavertex
iscalledadistancelabel.Weusethetermheightbecauseitismoresuggestiveoftheintuition
behindthealgorithm.Weretaintheuseofthetermrelabeltorefertotheoperationthatincreases
theheightofavertex.Theheightofavertexisrelatedtoitsdistancefromthesinkt,aswouldbe
foundinabreadthfirstsearchofthetransposeGT.

Pgina160

26.4Pushrelabelalgorithms 739

PUSH.u/
1//Applieswhen:uisoverflowing,cf.u/>0,andu:hD:hC1.
2//Action:Pushf.u/Dmin.u:ecf.u//unitsofflowfromuto.
3f.u/Dmin.u:ecf.u//
4if.u/2E
5 .u/:fD.u/:fCf.u/
6else.u/:fD.u/:f f .u/

7u:eDu:ef.u/
8 :eD:eCf.u/

ThecodeforPUSHoperatesasfollows.Becausevertexuhasapositiveexcessu:e
andtheresidualcapacityof.u/ispositive,wecanincreasetheflowfromuto
byf.u/Dmin.u:ecf.u//withoutcausingu:etobecomenegativeorthe
capacitycu/tobeexceeded.Line3computesthevaluef.u/,andlines46
updatef.Line5increasestheflowonedge.u/,becausewearepushingflow
overaresidualedgethatisalsoanoriginaledge.Line6decreasestheflowon
edge.u/,becausetheresidualedgeisactuallythereverseofanedgeinthe
originalnetwork.Finally,lines78updatetheexcessflowsintoverticesuand.
Thus,iffisapreflowbeforePUSHiscalled,itremainsapreflowafterward.
ObservethatnothinginthecodeforPUSHdependsontheheightsofuand,

https://translate.googleusercontent.com/translate_f 99/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
yetweprohibititfrombeinginvokedunlessu:hD:hC1.Thus,wepushexcess
flowdownhillonlybyaheightdifferentialof1.ByLemma26.12,noresidual
edgesexistbetweentwoverticeswhoseheightsdifferbymorethan1,andthus,
aslongastheattributehisindeedaheightfunction,wewouldgainnothingby
allowingflowtobepusheddownhillbyaheightdifferentialofmorethan1.
WecalltheoperationPUSH.u/apushfromuto.Ifapushoperationap
pliestosomeedge.u/leavingavertexu,wealsosaythatthepushoperation
appliestou.Itisasaturatingpushifedge.u/intheresidualnetworkbecomes
saturated(cf.u/D0afterward)otherwise,itisanonsaturatingpush.Ifan
edgebecomessaturated,itdisappearsfromtheresidualnetwork.Asimplelemma
characterizesoneresultofanonsaturatingpush.

Lemma26.13
Afteranonsaturatingpushfromuto,thevertexuisnolongeroverflowing.

ProofSincethepushwasnonsaturating,theamountofflowf.u/actually
pushedmustequalu:epriortothepush.Sinceu:eisreducedbythisamount,it
becomes0afterthepush.

Pgina161

740 Chapter26MaximumFlow

Therelabeloperation
ThebasicoperationRELABEL.u/appliesifuisoverflowingandifu:h:hfor
alledges.u/2Ef.Inotherwords,wecanrelabelanoverflowingvertexuif
foreveryvertexforwhichthereisresidualcapacityfromuto,flowcannotbe
pushedfromutobecauseisnotdownhillfromu.(Recallthatbydefinition,
neitherthesourcesnorthesinktcanbeoverflowing,andsosandtareineligible
forrelabeling.)

RELABEL.u/
1//Applieswhen:uisoverflowingandforall2Vsuchthat.u/2Ef,
wehaveu:h:h.
2//Action:Increasetheheightofu.
3u:hD1Cminf:hW.u/2Efg

WhenwecalltheoperationRELABEL.u/,wesaythatvertexuisrelabeled.Nota
thatwhenuisrelabeled,Efmustcontainatleastoneedgethatleavesu,sothat
theminimizationinthecodeisoveranonemptyset.Thispropertyfollowsfrom
theassumptionthatuisoverflowing,whichinturntellsusthat
x x
u:eD f.u/ f.u/>0:
2V 2V
Sinceallflowsarenonnegative,wemustthereforehaveatleastonevertexsuch
that.u/:f>0.Butthen,cf.u/>0,whichimpliesthat.u/2Ef.El
operationRELABEL.u/thusgivesuthegreatestheightallowedbytheconstraints
onheightfunctions.

Thegenericalgorithm
Thegenericpushrelabelalgorithmusesthefollowingsubroutinetocreateanini
tialpreflowintheflownetwork.

INITIALIZEPREFLOW.Gs/
1foreachvertex2G:V
2 :hD0
3 :eD0
4foreachedge.u/2G:E
5 .u/:fD0
6s:hDjG:Vj
7foreachvertex2s:Adj
8 .s/:fDcs/
9 :eDcs/
10 s:eDs:ecs/

Pgina162

26.4Pushrelabelalgorithms 741

INITIALIZEPREFLOWcreatesaninitialpreflowfdefinedby
https://translate.googleusercontent.com/translate_f 100/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
(
cu/ifuDs
.u/:fD (26.15)
0 otherwise:
Thatis,wefilltocapacityeachedgeleavingthesources,andallotheredgescarry
noflow.Foreachvertexadjacenttothesource,weinitiallyhave:eDcs/,
andweinitializes:etothenegativeofthesumofthesecapacities.Thegeneric
algorithmalsobeginswithaninitialheightfunctionh,givenby
(
jVjifuDs
u:hD (26.16)
0 otherwise:
Equation(26.16)definesaheightfunctionbecausetheonlyedges.u/forwhich
u:h>:hC1arethoseforwhichuDs,andthoseedgesaresaturated,which
meansthattheyarenotintheresidualnetwork.
Initialization,followedbyasequenceofpushandrelabeloperations,executed
innoparticularorder,yieldstheGENERICPUSHRELABELalgorithm:

GENERICPUSHRELABEL.G/
1INITIALIZEPREFLOW.Gs/
2whilethereexistsanapplicablepushorrelabeloperation
3 selectanapplicablepushorrelabeloperationandperformit

Thefollowinglemmatellsusthataslongasanoverflowingvertexexists,atleast
oneofthetwobasicoperationsapplies.

Lemma26.14(Anoverflowingvertexcanbeeitherpushedorrelabeled)
LetGD.VE/beaflownetworkwithsourcesandsinkt,letfbeapreflow,
andlethbeanyheightfunctionforf.Ifuisanyoverflowingvertex,theneithera
pushorrelabeloperationappliestoit.

ProofForanyresidualedge.u/,wehavehu/h./C1becausehisa
heightfunction.Ifapushoperationdoesnotapplytoanoverflowingvertexu,
thenforallresidualedges.u/,wemusthavehu/<h./C1,whichimplies
hu/h./.Thus,arelabeloperationappliestou.

Correctnessofthepushrelabelmethod
Toshowthatthegenericpushrelabelalgorithmsolvesthemaximumflowprob
lem,weshallfirstprovethatifitterminates,thepreflowfisamaximumflow.
Weshalllaterprovethatitterminates.Westartwithsomeobservationsaboutthe
heightfunctionh.

Pgina163

742 Chapter26MaximumFlow

Lemma26.15(Vertexheightsneverdecrease)
DuringtheexecutionoftheGENERICPUSHRELABELprocedureonaflownet
workGD.VE/,foreachvertexu2V,theheightu:hneverdecreases.Ms
over,wheneverarelabeloperationisappliedtoavertexu,itsheightu:hincreases
byatleast1.

ProofBecausevertexheightschangeonlyduringrelabeloperations,itsuffices
toprovethesecondstatementofthelemma.Ifvertexuisabouttoberela
beled,thenforallverticessuchthat.u/2Ef,wehaveu:h:h.Thus,
u:h<1Cminf:hW.u/2Efg,andsotheoperationmustincreaseu:h.

Lemma26.16
LetGD.VE/beaflownetworkwithsourcesandsinkt.Thentheexecutionof
GENERICPUSHRELABELonGmaintainstheattributehasaheightfunction.

ProofTheproofisbyinductiononthenumberofbasicoperationsperformed.
Initially,hisaheightfunction,aswehavealreadyobserved.
Weclaimthatifhisaheightfunction,thenanoperationRELABEL.u/leavesh
aheightfunction.Ifwelookataresidualedge.u/2Efthatleavesu,then
theoperationRELABEL.u/ensuresthatu:h:hC1afterward.Nowconsider
aresidualedge.wu/thatentersu.ByLemma26.15,w:hu:hC1beforethe
operationRELABEL.u/impliesw:h<u:hC1afterward.Thus,theoperation
RELABEL.u/leaveshaheightfunction.
Now,consideranoperationPUSH.u/.Thisoperationmayaddtheedge.u/
toEf,anditmayremove.u/fromEf.Intheformercase,wehave
:hDu:h1<u:hC1,andsohremainsaheightfunction.Inthelattercase,
removing.u/fromtheresidualnetworkremovesthecorrespondingconstraint,
andhagainremainsaheightfunction.

Thefollowinglemmagivesanimportantpropertyofheightfunctions.

Lemma26.17

https://translate.googleusercontent.com/translate_f 101/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
LetGD.VE/beaflownetworkwithsourcesandsinkt,letfbeapreflow
inG,andlethbeaheightfunctiononV.Thenthereisnopathfromthesources
tothesinktintheresidualnetworkGf.

ProofAssumeforthesakeofcontradictionthatGfcontainsapathpfromstot,
wherepDh01:::ki,0Ds,andkDt.Withoutlossofgenerality,p
isasimplepath,andsok<jVj.ForiD01:::k1,edge.iiC1/2Ef.
Becausehisaheightfunction,h.i/h.iC1/C1foriD01:::k1.Com
biningtheseinequalitiesoverpathpyieldshs/ht/Ck.Butbecauseht/D0,

Pgina164

26.4Pushrelabelalgorithms 743

wehavehs/k<jVj,whichcontradictstherequirementthaths/DjVjina
heightfunction.

Wearenowreadytoshowthatifthegenericpushrelabelalgorithmterminates,
thepreflowitcomputesisamaximumflow.

Theorem26.18(Correctnessofthegenericpushrelabelalgorithm)
IfthealgorithmGENERICPUSHRELABELterminateswhenrunonaflownet
workGD.VE/withsourcesandsinkt,thenthepreflowfitcomputesisa
maximumflowforG.

ProofWeusethefollowingloopinvariant:
Eachtimethewhilelooptestinline2inGENERICPUSHRELABELis
executed,fisapreflow.

Initialization:INITIALIZEPREFLOWmakesfapreflow.
Maintenance:Theonlyoperationswithinthewhileloopoflines23arepushand
relabel.Relabeloperationsaffectonlyheightattributesandnottheflowvalues
hencetheydonotaffectwhetherfisapreflow.Asarguedonpage739,iffis
apreflowpriortoapushoperation,itremainsapreflowafterward.
Termination:Attermination,eachvertexinV fstgmusthaveanexcessof0,
becausebyLemma26.14andtheinvariantthatfisalwaysapreflow,thereare
nooverflowingvertices.Therefore,fisaflow.Lemma26.16showsthathis
aheightfunctionattermination,andthusLemma26.17tellsusthatthereisno
pathfromstotintheresidualnetworkGf.Bythemaxflowmincuttheorem
(Theorem26.6),therefore,fisamaximumflow.

Analysisofthepushrelabelmethod
Toshowthatthegenericpushrelabelalgorithmindeedterminates,weshallbound
thenumberofoperationsitperforms.Weboundseparatelyeachofthethreetypes
ofoperations:relabels,saturatingpushes,andnonsaturatingpushes.Withknowl
edgeofthesebounds,itisastraightforwardproblemtoconstructanalgorithmthat
runsinOV2E/time.Beforebeginningtheanalysis,however,weproveanim
portantlemma.Recallthatweallowedgesintothesourceintheresidualnetwork.

Lemma26.19
LetGD.VE/beaflownetworkwithsourcesandsinkt,andletfbeapreflow
inG.Then,foranyoverflowingvertexx,thereisasimplepathfromxtosinthe
residualnetworkGf.

Pgina165

744 Chapter26MaximumFlow

ProofForanoverflowingvertexx,letUDfWthereexistsasimplepathfromx
toinGfg,andsupposeforthesakeofcontradictionthats62U.LetUDVU.
Wetakethedefinitionofexcessfromequation(26.14),sumoverallvertices
inU,andnotethatVDU[U,toobtain
x
eu/
u2U !
x x x
re f.u/ f.u/
u2U
2V 2V ! !!
x x x x x
re f.u/C f.u/ f.u/C f.u/
u2U
x x 2U x x 2U x 2U
x 2U
x x

https://translate.googleusercontent.com/translate_f 102/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
re f.u/C f.u/ f.u/ f.u/
u2U
x x2U xu2Ux2U u2U 2U u2U 2U
re f.u/ f.u/:
u2U 2U u2U 2U
PAG
Weknowthatthequantity u2Ueu/mustbepositivebecauseex/>0,x2U,
allverticesotherthanshavenonnegativeexcess,and,byassumption,s62U.Thus,
wehave
x x x x
f.u/ f.u/>0: (26.17)
u2U 2U u2U 2U
Alledgeflowsarenonnegative,andsoforequation(26.17)tohold,wemusthave
PAG PAG
u2U 2Uf.u/>0.Hence,theremustexistatleastonepairofvertices
u02Uand02Uwithf.0u0/>0.But,iff.0u0/>0,theremustbea
residualedge.u00/,whichmeansthatthereisasimplepathfromxto0(the
pathxu0!0),thuscontradictingthedefinitionofU.

Thenextlemmaboundstheheightsofvertices,anditscorollaryboundsthe
numberofrelabeloperationsthatareperformedintotal.

Lemma26.20
LetGD.VE/beaflownetworkwithsourcesandsinkt.Atanytimeduring
theexecutionofGENERICPUSHRELABELonG,wehaveu:h2jVj1forall
verticesu2V.

ProofTheheightsofthesourcesandthesinktneverchangebecausethese
verticesarebydefinitionnotoverflowing.Thus,wealwayshaves:hDjVjand
t:hD0,bothofwhicharenogreaterthan2jVj1.
Nowconsideranyvertexu2Vfstg.Initially,u:hD02jVj1.Weshall
showthataftereachrelabelingoperation,westillhaveu:h2jVj1.Whenuis

Page166

26.4Pushrelabelalgorithms 745

relabeled,itisoverflowing,andLemma26.19tellsusthatthereisasimplepathp
fromutosinGf.LetpDh01:::ki,where0Du,kDs,andkjVj1
becausepissimple.ForiD01:::K 1,wehave.iiC1/2Ef,and
therefore,byLemma26.16,i:hiC1:hC1.Expandingtheseinequalitiesover
pathpyieldsu:hD0:hk:hCks:hC.jVj1/D2jVj1.

Corollary26.21(Boundonrelabeloperations)
LetGD.VE/beaflownetworkwithsourcesandsinkt.Then,duringthe
executionofGENERICPUSHRELABELonG,thenumberofrelabeloperationsis
atmost2jVj1pervertexandatmost.2jVj1/.jVj2/<2jVj 2 engeneral.

ProofOnlythejVj2verticesinVfstgmayberelabeled.Letu2Vfstg.
TheoperationRELABEL.u/increasesu:h.Thevalueofu:hisinitially0andby
Lemma26.20,itgrowstoatmost2jVj1.Thus,eachvertexu2V fsTg
isrelabeledatmost2jVj1times,andthetotalnumberofrelabeloperations
performedisatmost.2jVj1/.jVj2/<2jVj 2.

Lemma26.20alsohelpsustoboundthenumberofsaturatingpushes.

Lemma26.22(Boundonsaturatingpushes)
DuringtheexecutionofGENERICPUSHRELABELonanyflownetworkGD
.VE/,thenumberofsaturatingpushesislessthan2jVjjEj.

ProofForanypairofverticesu2V,wewillcountthesaturatingpushes
fromutoandfromtoutogether,callingthemthesaturatingpushesbetweenu
Y.Ifthereareanysuchpushes,atleastoneof.u/and.u/isactually
anedgeinE.Now,supposethatasaturatingpushfromuto hasoccurred.
Atthattime,:hDu:h 1.Inorderforanotherpushfromuto queseproduzca
later,thealgorithmmustfirstpushflowfromtou,whichcannothappenuntil
:hDu:hC1.Sinceu:hneverdecreases,inorderfor:hDu:hC1,the
valueof:hmustincreasebyatleast2.Likewise,u:hmustincreasebyatleast2
betweensaturatingpushesfromtou.Heightsstartat0and,byLemma26.20,
neverexceed2jVj1,whichimpliesthatthenumberoftimesanyvertexcanhave
itsheightincreaseby2islessthanjVj.Sinceatleastoneofu:hand:hmust
increaseby2betweenanytwosaturatingpushesbetweenuand,therearefewer
than2jVjsaturatingpushesbetweenuand.Multiplyingbythenumberofedges
givesaboundoflessthan2jVjjEjonthetotalnumberofsaturatingpushes.

Thefollowinglemmaboundsthenumberofnonsaturatingpushesinthegeneric
pushrelabelalgorithm.

https://translate.googleusercontent.com/translate_f 103/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Page167

746 Chapter26MaximumFlow

Lemma26.23(Boundonnonsaturatingpushes)
DuringtheexecutionofGENERICPUSHRELABELonanyflownetworkGD
.VE/,thenumberofnonsaturatingpushesislessthan4jVj 2 .jVjCjEj/.
PAG
ProofDefineapotentialfunctionD :h.Initially,D0,andthe
We./>0
valueofmaychangeaftereachrelabeling,saturatingpush,andnonsaturating
push.Wewillboundtheamountthatsaturatingpushesandrelabelingscancon
tributetotheincreaseof.Thenwewillshowthateachnonsaturatingpushmust
decreasebyatleast1,andwillusetheseboundstoderiveanupperboundonthe
numberofnonsaturatingpushes.
Letusexaminethetwowaysinwhichmightincrease.First,relabelinga
vertexuincreasesbylessthan2jVj,sincethesetoverwhichthesumistakenis
thesameandtherelabelingcannotincreaseu'sheightbymorethanitsmaximum
possibleheight,which,byLemma26.20,isatmost2jVj1.Second,asaturating
pushfromavertexutoavertexincreasesbylessthan2jVj,sincenoheights
changeandonlyvertex,whoseheightisatmost2jVj1,canpossiblybecome
overflowing.
Nowweshowthatanonsaturatingpushfromutodecreasesbyatleast1.
Porqu?Beforethenonsaturatingpush,uwasoverflowing,andmayormaynot
havebeenoverflowing.ByLemma26.13,uisnolongeroverflowingafterthe
push.Inaddition,unlessisthesource,itmayormaynotbeoverflowingafter
thepush.Therefore,thepotentialfunctionhasdecreasedbyexactlyu:h,andit
hasincreasedbyeither0or:h.Sinceu:h :hD1,theneteffectisthatthe
potentialfunctionhasdecreasedbyatleast1.
Thus,duringthecourseofthealgorithm,thetotalamountofincreaseinis
duetorelabelingsandsaturatedpushes,andCorollary26.21andLemma26.22
constraintheincreasetobelessthan.2jVj/.2jVj 2/C.2jVj/.2jVjjEj/D
4jVj 2 .jVjCjEj/.Since 0,thetotalamountofdecrease,andthereforethe
totalnumberofnonsaturatingpushes,islessthan4jVj 2 .jVjCjEj/.

Havingboundedthenumberofrelabelings,saturatingpushes,andnonsatu
ratingpush,wehavesetthestageforthefollowinganalysisoftheGENERIC
PUSHRELABELprocedure,andhenceofanyalgorithmbasedonthepushrelabel
Mtodo.

Theorem26.24
DuringtheexecutionofGENERICPUSHRELABELonanyflownetworkGD
.VE/,thenumberofbasicoperationsisOV2E/.

ProofImmediatefromCorollary26.21andLemmas26.22and26.23.

Pgina168

26.4Pushrelabelalgorithms 747

Thus,thealgorithmterminatesafterOV2E/operations.Allthatremainsis
togiveanefficientmethodforimplementingeachoperationandforchoosingan
appropriateoperationtoexecute.

Corollary26.25
Thereisanimplementationofthegenericpushrelabelalgorithmthatrunsin
OV2E/timeonanyflownetworkGD.VE/.

ProofExercise26.42asksyoutoshowhowtoimplementthegenericalgorithm
withanoverheadofOV/perrelabeloperationandO.1/perpush.Italsoasks
youtodesignadatastructurethatallowsyoutopickanapplicableoperationin
O.1/time.Thecorollarythenfollows.

Exercises

26.41
Provethat,aftertheprocedureINITIALIZEPREFLOW.Gs/terminates,wehave
s:ejfj,wherefisamaximumflowforG.

26.42
ShowhowtoimplementthegenericpushrelabelalgorithmusingOV/timeper
relabeloperation,O.1/timeperpush,andO.1/timetoselectanapplicableoper
ation,foratotaltimeofOV2E/.

https://translate.googleusercontent.com/translate_f 104/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
26.43
ProvethatthegenericpushrelabelalgorithmspendsatotalofonlyO.VE/time
inperformingalltheOV2/relabeloperations.

26.44
SupposethatwehavefoundamaximumflowinaflownetworkGD.VE/using
apushrelabelalgorithm.GiveafastalgorithmtofindaminimumcutinG.

26.45
Giveanefficientpushrelabelalgorithmtofindamaximummatchinginabipartite
grafico.Analyzeyouralgorithm.

26.46
SupposethatalledgecapacitiesinaflownetworkGD.VE/areintheset
f12:::kg.Analyzetherunningtimeofthegenericpushrelabelalgorithmin
termsofjVj,jEj,andk.(Hint:Howmanytimescaneachedgesupportanonsat
uratingpushbeforeitbecomessaturated?)

Pgina169

748 Chapter26MaximumFlow

26.47
Showthatwecouldchangeline6ofINITIALIZEPREFLOWto

6s:hDjG:Vj2

withoutaffectingthecorrectnessorasymptoticperformanceofthegenericpush
relabelalgorithm.

26.48
Letf.u/bethedistance(numberofedges)fromutointheresidualnet
workGf.ShowthattheGENERICPUSHRELABELproceduremaintainsthe
propertiesthatu:h<jVjimpliesu:hf.ut/andthatu:h jVjimplies
u:hjVjf.us/.

26.49?
Asinthepreviousexercise,letf.u/bethedistancefromutointheresidual
networkGf.Showhowtomodifythegenericpushrelabelalgorithmtomaintain
thepropertythatu:h<jVjimpliesu:hDf.ut/andthatu:h jVjimplies
u:hjVjDf.us/.Thetotaltimethatyourimplementationdedicatestomain
tainingthispropertyshouldbeO.VE/.

26.410
ShowthatthenumberofnonsaturatingpushesexecutedbytheGENERICPUSH
RELABELprocedureonaflownetworkGD.VE/isatmost4jVj 2 jEjfor
jVj4.

?26.5Therelabeltofrontalgorithm

Thepushrelabelmethodallowsustoapplythebasicoperationsinanyorderat
all.Bychoosingtheordercarefullyandmanagingthenetworkdatastructureeffi
ciently,however,wecansolvethemaximumflowproblemfasterthantheOV2E/
boundgivenbyCorollary26.25.Weshallnowexaminetherelabeltofrontalgo
rithm,apushrelabelalgorithmwhoserunningtimeisOV3/,whichisasymptot
icallyatleastasgoodasOV2E/,andevenbetterfordensenetworks.
Therelabeltofrontalgorithmmaintainsalistoftheverticesinthenetwork.
Beginningatthefront,thealgorithmscansthelist,repeatedlyselectinganover
flowingvertexuandthendischargingit,thatis,performingpushandrelabel
operationsuntilunolongerhasapositiveexcess.Wheneverwerelabelaver
tex,wemoveittothefrontofthelist(hencethenamerelabeltofront)andthe
algorithmbeginsitsscananew.

Pgina170

26.5Therelabeltofrontalgorithm 749

Thecorrectnessandanalysisoftherelabeltofrontalgorithmdependonthe
notionofadmissibleedges:thoseedgesintheresidualnetworkthroughwhich
flowcanbepushed.Afterprovingsomepropertiesaboutthenetworkofadmissible
edges,weshallinvestigatethedischargeoperationandthenpresentandanalyzethe

https://translate.googleusercontent.com/translate_f 105/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
relabeltofrontalgorithmitself.

Admissibleedgesandnetworks
IfGD.VE/isaflownetworkwithsourcesandsinkt,fisapreflowinG,andh
isaheightfunction,thenwesaythat.u/isanadmissibleedgeifcf.u/>0
andhu/Dh./C1.Otherwise,.u/isinadmissible.Theadmissiblenetwork
isGfhD.VEfh/,whereEfhisthesetofadmissibleedges.
Theadmissiblenetworkconsistsofthoseedgesthroughwhichwecanpushflow.
Thefollowinglemmashowsthatthisnetworkisadirectedacyclicgraph(dag).

Lemma26.26(Theadmissiblenetworkisacyclic)
IfGD.VE/isaflownetwork,fisapreflowinG,andhisaheightfunction
onG,thentheadmissiblenetworkGfhD.VEfh/isacyclic.

ProofTheproofisbycontradiction.SupposethatGfhcontainsacyclepD
h01:::ki,where0Dkandk>0.Sinceeachedgeinpisadmissible,we
haveh.i1/Dh.i/C1foriD12:::KSummingaroundthecyclegives
xK xK
marido.i1/D .h.i/C1/
ID1 ID1
xK
re marido.i/Ck:
ID1
Becauseeachvertexincyclepappearsonceineachofthesummations,wederive
thecontradictionthat0Dk.

Thenexttwolemmasshowhowpushandrelabeloperationschangetheadmis
siblenetwork.

Lemma26.27
LetGD.VE/beaflownetwork,letfbeapreflowinG,andsupposethatthe
attributehisaheightfunction.Ifavertexuisoverflowingand.u/isanad
missibleedge,thenPUSH.u/applies.Theoperationdoesnotcreateanynew
admissibleedges,butitmaycause.u/tobecomeinadmissible.

Pgina171

750 Chapter26MaximumFlow

ProofBythedefinitionofanadmissibleedge,wecanpushflowfromuto.
Sinceuisoverflowing,theoperationPUSH.u/applies.Theonlynewresidual
edgethatpushingflowfromutocancreateis.u/.Since:hDu:h 1,
edge.u/cannotbecomeadmissible.Iftheoperationisasaturatingpush,then
cf.u/D0afterwardand.u/becomesinadmissible.

Lemma26.28
LetGD.VE/beaflownetwork,letfbeapreflowinG,andsupposethat
theattributehisaheightfunction.Ifavertexuisoverflowingandthereareno
admissibleedgesleavingu,thenRELABEL.u/applies.Aftertherelabeloperation,
thereisatleastoneadmissibleedgeleavingu,buttherearenoadmissibleedges
enteringu.

ProofIfuisoverflowing,thenbyLemma26.14,eitherapushorarelabelop
erationappliestoit.Iftherearenoadmissibleedgesleavingu,thennoflow
canbepushedfromuandsoRELABEL.u/applies.Aftertherelabeloperation,
u:hD1Cminf:hW.u/2Efg.Thus,ifisavertexthatrealizesthemini
muminthisset,theedge.u/becomesadmissible.Hence,aftertherelabel,there
isatleastoneadmissibleedgeleavingu.
Toshowthatnoadmissibleedgesenteruafterarelabeloperation,supposethat
thereisavertexsuchthat.u/isadmissible.Then,:hDu:hC1afterthe
relabel,andso:h>u:hC1justbeforetherelabel.ButbyLemma26.12,no
residualedgesexistbetweenverticeswhoseheightsdifferbymorethan1.More
over,relabelingavertexdoesnotchangetheresidualnetwork.Thus,.u/isnot
intheresidualnetwork,andhenceitcannotbeintheadmissiblenetwork.

Neighborlists
Edgesintherelabeltofrontalgorithmareorganizedintoneighborlists.Given
aflownetworkGD.VE/,theneighborlistu:Nforavertexu2Visasingly
linkedlistoftheneighborsofuinG.Thus,vertexappearsinthelistu:Nif
.u/2Eor.u/2E.Theneighborlistu:Ncontainsexactlythosevertices
forwhichtheremaybearesidualedge.u/.Theattributeu:N:headpointsto
thefirstvertexinu:N,and:nextneighborpointstothevertexfollowingina
neighborlistthispointerisNILifisthelastvertexintheneighborlist.

https://translate.googleusercontent.com/translate_f 106/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Therelabeltofrontalgorithmcyclesthrougheachneighborlistinanarbitrary
orderthatisfixedthroughouttheexecutionofthealgorithm.Foreachvertexu,
theattributeu:currentpointstothevertexcurrentlyunderconsiderationinu:N.
Initially,u:currentissettou:N:head.

Pgina172

26.5Therelabeltofrontalgorithm 751

Discharginganoverflowingvertex
Anoverflowingvertexuisdischargedbypushingallofitsexcessflowthrough
admissibleedgestoneighboringvertices,relabelinguasnecessarytocauseedges
leavingutobecomeadmissible.Thepseudocodegoesasfollows.

DISCHARGE.u/
1whileu:e>0
2 Du:current
3 if==NIL
4 RELABEL.u/
5 u:currentDu:N:head
6 elseifcf.u/>0andu:h==:hC1
7 PUSH.u/
8 elseu:currentD:nextneighbor

Figure26.9stepsthroughseveraliterationsofthewhileloopoflines18,which
executesaslongasvertexuhaspositiveexcess.Eachiterationperformsexactly
oneofthreeactions,dependingonthecurrentvertexintheneighborlistu:N.
1.Si isNIL,thenwehaverunofftheendofu:N.Line4relabelsvertexu,
andthenline5resetsthecurrentneighborofutobethefirstoneinu:N.
(Lemma26.29belowstatesthattherelabeloperationappliesinthissituation.)
2.If isnonNILand.u/isanadmissibleedge(determinedbythetestin
line6),thenline7pushessome(orpossiblyall)ofu'sexcesstovertex.
3.IfisnonNILbut.u/isinadmissible,thenline8advancesu:currentone
positionfurtherintheneighborlistu:N.
ObservethatifDISCHARGEiscalledonanoverflowingvertexu,thenthelast
actionperformedbyDISCHARGEmustbeapushfromu.Porqu?Theprocedure
terminatesonlywhenu:ebecomeszero,andneithertherelabeloperationnorad
vancingthepointeru:currentaffectsthevalueofu:e.
WemustbesurethatwhenPUSHorRELABELiscalledbyDISCHARGE,the
operationapplies.Thenextlemmaprovesthisfact.

Lemma26.29
IfDISCHARGEcallsPUSH.u/inline7,thenapushoperationappliesto.u/.
IfDISCHARGEcallsRELABEL.u/inline4,thenarelabeloperationappliestou.

ProofThetestsinlines1and6ensurethatapushoperationoccursonlyifthe
operationapplies,whichprovesthefirststatementinthelemma.

Pgina173

752 Chapter26MaximumFlow

6
S
5 26 1 2 3 4
4 S S S S
14/14
(un) 3 x x x x
2 Z Z Z Z
1 x
0 5/5 Y Z
0 8
19 0

6
S 5 6 7
5 26
4 14/14 S S S
(segundo)3 x x x
2 Z Z Z
x 5/5 Y
1 0 19 8
0 Z
0
https://translate.googleusercontent.com/translate_f 107/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

6
S
5 26 8 9
4 14/14 S S
(do) 3 x x
2 Z Z
1 x 5/5 Y 8/8
0 11 Z
0 8

Figure26.9Dischargingavertexy.Ittakes15iterationsofthewhileloopofDISCHARGEtopush
alltheexcessflowfromy.Onlytheneighborsofyandedgesoftheflownetworkthatenterorleavey
sonexhibidos.Ineachpartofthefigure,thenumberinsideeachvertexisitsexcessatthebeginningof
thefirstiterationshowninthepart,andeachvertexisshownatitsheightthroughoutthepart.los
neighborlisty:Natthebeginningofeachiterationappearsontheright,withtheiterationnumber
ontop.Theshadedneighborisy:current.(a)Initially,thereare19unitsofexcesstopushfromy,
andy:currentDs.Iterations1,2,and3justadvancey:current,sincetherearenoadmissibleedges
leavingy.Initeration4,y:currentDNIL(shownbytheshadingbeingbelowtheneighborlist),
andsoyisrelabeledandy:currentisresettotheheadoftheneighborlist.(b)Afterrelabeling,
vertexyhasheight1.Initerations5and6,edges.ys/and.yx/arefoundtobeinadmissible,but
iteration7pushes8unitsofexcessflowfromyto.Becauseofthepush,y:currentdoesnotadvance
inthisiteration.(c)Becausethepushiniteration7saturatededge.y/,itisfoundinadmissiblein
iteration8.Initeration9,y:currentDNIL,andsovertexyisagainrelabeledandy:currentisreset.

Pgina174

26.5Therelabeltofrontalgorithm 753

6
S
5 26 10 11
4 14/14 S S
(re) 3 x x
Y
2 Z Z
1 x 5/5 11 8/8
0 Z
0 8

6
S
5 26 12 13 14
4 14/14 S S S
(mi) 3 x x x
Y Z Z Z
2 5 6 8/8
1 x
5 Z
0 8
Y
6 14/14 6
S
5 26 15
4 8/8 S
5
(f) 3 x
2 Z
1 x
5 Z
0 8
Y
6 8/14 0
S
5 20
4 8/8
5
(gramo) 3
2
1 x
5 Z
0 8

Figure26.9,continued(d)Initeration10,.ys/isinadmissible,butiteration11pushes5units
ofexcessflowfromytox.(e)Becausey:currentdidnotadvanceiniteration11,iteration12
finds.yx/tobeinadmissible.Iteration13finds.y/inadmissible,anditeration14relabelsver
texyandresetsy:current.(f)Iteration15pushes6unitsofexcessflowfromytos.(g)Vertexy
nowhasnoexcessflow,andDISCHARGEterminates.Inthisexample,DISCHARGEbothstartsand
finisheswiththecurrentpointerattheheadoftheneighborlist,butingeneralthisneednotbethe
case.

Pgina175
https://translate.googleusercontent.com/translate_f 108/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

754 Chapter26MaximumFlow

Toprovethesecondstatement,accordingtothetestinline1andLemma26.28,
weneedonlyshowthatalledgesleavinguareinadmissible.Ifacallto
DISCHARGE.u/startswiththepointeru:currentattheheadofu'sneighborlist
andfinisheswithitofftheendofthelist,thenallofu'soutgoingedgesarein
admissibleandarelabeloperationapplies.Itispossible,however,thatduringa
calltoDISCHARGE.u/,thepointeru:currenttraversesonlypartofthelistbe
foretheprocedurereturns.CallstoDISCHARGEonotherverticesmaythenoc
cur,butu:currentwillcontinuemovingthroughthelistduringthenextcallto
DISCHARGE.u/.Wenowconsiderwhathappensduringacompletepassthrough
thelist,whichbeginsattheheadofu:Nandfinisheswithu:currentDNIL.Unavez
u:currentreachestheendofthelist,theprocedurerelabelsuandbeginsanew
pass.Fortheu:currentpointertoadvancepastavertex2u:Nduringapass,the
edge.u/mustbedeemedinadmissiblebythetestinline6.Thus,bythetime
thepasscompletes,everyedgeleavinguhasbeendeterminedtobeinadmissible
atsometimeduringthepass.Thekeyobservationisthatattheendofthepass,
everyedgeleavinguisstillinadmissible.Porqu?ByLemma26.27,pushescannot
createanyadmissibleedges,regardlessofwhichvertextheflowispushedfrom.
Thus,anyadmissibleedgemustbecreatedbyarelabeloperation.Butthevertexu
isnotrelabeledduringthepass,andbyLemma26.28,anyothervertexthatis
relabeledduringthepass(resultingfromacallofDISCHARGE./)hasnoentering
admissibleedgesafterrelabeling.Thus,attheendofthepass,alledgesleavingu
remaininadmissible,whichcompletestheproof.

Therelabeltofrontalgorithm
Intherelabeltofrontalgorithm,wemaintainalinkedlistLconsistingofallver
ticesinV fstg.AkeypropertyisthattheverticesinLaretopologicallysorted
accordingtotheadmissiblenetwork,asweshallseeintheloopinvariantthatfol
lows.(RecallfromLemma26.26thattheadmissiblenetworkisadag.)
Thepseudocodefortherelabeltofrontalgorithmassumesthattheneighbor
listsu:Nhavealreadybeencreatedforeachvertexu.Italsoassumesthatu:next
pointstothevertexthatfollowsuinlistLandthat,asusual,u:nextDNILifuis
thelastvertexinthelist.

Pgina176

26.5Therelabeltofrontalgorithm 755

RELABELTOFRONT.Gst/
1INITIALIZEPREFLOW.Gs/
2LDG:Vfstg,inanyorder
3foreachvertexu2G:VfsTg
4 u:currentDu:N:head
5uDL:head
6whileuNIL
7 oldheightDu:h
8 DISCHARGE.u/
9 ifu:h>oldheight
10 moveutothefrontoflistL
11 uDu:next

Therelabeltofrontalgorithmworksasfollows.Line1initializesthepreflow
andheightstothesamevaluesasinthegenericpushrelabelalgorithm.Lnea2
initializesthelistLtocontainallpotentiallyoverflowingvertices,inanyorder.
Lines34initializethecurrentpointerofeachvertexutothefirstvertexinus
neighborlist.
AsFigure26.10illustrates,thewhileloopoflines611runsthroughthelistL,
dischargingvertices.Line5makesitstartwiththefirstvertexinthelist.Cada
timethroughtheloop,line8dischargesavertexu.Ifuwasrelabeledbythe
DISCHARGEprocedure,line10movesittothefrontoflistL.Wecandetermine
whetheruwasrelabeledbycomparingitsheightbeforethedischargeoperation,
savedintothevariableoldheightinline7,withitsheightafterward,inline9.
Line11makesthenextiterationofthewhileloopusethevertexfollowinguin
listL.Ifline10movedutothefrontofthelist,thevertexusedinthenextiteration

https://translate.googleusercontent.com/translate_f 109/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
istheonefollowinguinitsnewpositioninthelist.
ToshowthatRELABELTOFRONTcomputesamaximumflow,weshallshow
thatitisanimplementationofthegenericpushrelabelalgorithm.First,ob
servethatitperformspushandrelabeloperationsonlywhentheyapply,since
Lemma26.29guaranteesthatDISCHARGEperformsthemonlywhentheyapply.
ItremainstoshowthatwhenRELABELTOFRONTterminates,nobasicopera
tionsapply.Theremainderofthecorrectnessargumentreliesonthefollowing
loopinvariant:

Ateachtestinline6ofRELABELTOFRONT,listLisatopologicalsort
oftheverticesintheadmissiblenetworkGfhD.VEfh/,andnovertex
beforeuinthelisthasexcessflow.

Initialization:ImmediatelyafterINITIALIZEPREFLOWhasbeenrun,s:hDjVj
and:hD0forall 2V fsg.SincejVj2(becauseVcontainsat

Pgina177

756 Chapter26MaximumFlow

6
5 S
26 L: x Y Z
4 N: S S x
(un) 3 12/1214/14 Y x Y
2 Z Z T
1 T
0 x 5 Y 8 Z 10 T
12 14 0 0
7 diecisis
6
S
5 26 L: x Y Z
4 12/1214/14 N: S S x
(segundo)
3 Y x Y
2 7/16 Z Z T
x 7
1 0 5/5 T
0 Y 8 Z 10 T
19 0 7

Y
6 8/14 0
5 S L: Y x Z
20
4 12/12 8/8 N: S S x
5
(do) 3 x Y Y
2 7/16 Z Z T
1 x T
5 7 Z T
0 10
8 7

Figure26.10TheactionofRELABELTOFRONT.(a)Aflownetworkjustbeforethefirstiteration
ofthewhileloop.Initially,26unitsofflowleavesources.Ontherightisshowntheinitiallist
LDhxyi,whereinitiallyuDx.UndereachvertexinlistLisitsneighborlist,withthecurrent
neighborshaded.Vertexxisdischarged.Itisrelabeledtoheight1,5unitsofexcessflowarepushed
toy,andthe7remainingunitsofexcessarepushedtothesinkt.Becausexisrelabeled,itmoves
totheheadofL,whichinthiscasedoesnotchangethestructureofL.(b)Afterx,thenextvertex
inLthatisdischargedisy.Figure26.9showsthedetailedactionofdischargingyinthissituation.
Becauseyisrelabeled,itismovedtotheheadofL.(c)VertexxnowfollowsyinL,andsoitis
againdischarged,pushingall5unitsofexcessflowtot.Becausevertexxisnotrelabeledinthis
dischargeoperation,itremainsinplaceinlistL.

Pgina178

26.5Therelabeltofrontalgorithm 757

6 Y
S 8/14 0
5 20 L: Y x Z
4 12/12 8/8 N: S S x
5
(re) 3 x Y Y
2 12/16 Z Z T
1 x T
0 7 Z T
0 10

https://translate.googleusercontent.com/translate_f 110/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
8 12

6 Y
S 8/14 0
5 20 L: Z Y x
4 8/8 N: x S S
12/12 5
(mi) 3 Y x Y
2 T Z Z
1 x 7 Z T
0 8/10
12/16 0 T
0 20

Figure26.10,continued(d)SincevertexfollowsvertexxinL,itisdischarged.Itisrelabeled
toheight1andall8unitsofexcessflowarepushedtot.Becauseisrelabeled,itmovestothe
frontofL.(e)VertexynowfollowsvertexinLandisthereforedischarged.Butbecauseyhasno
excess,DISCHARGEimmediatelyreturns,andyremainsinplaceinL.Vertexxisthendischarged.
Becauseit,too,hasnoexcess,DISCHARGEagainreturns,andxremainsinplaceinL.RELABEL
TOFRONThasreachedtheendoflistLandterminates.Therearenooverflowingvertices,andthe
preflowisamaximumflow.

leastsandt),noedgecanbeadmissible.Thus,EfhD,andanyorderingof
V fstgisatopologicalsortofGfh.
BecauseuisinitiallytheheadofthelistL,therearenoverticesbeforeitand
sotherearenonebeforeitwithexcessflow.
Maintenance:Toseethateachiterationofthewhileloopmaintainsthetopolog
icalsort,westartbyobservingthattheadmissiblenetworkischangedonlyby
pushandrelabeloperations.ByLemma26.27,pushoperationsdonotcause
edgestobecomeadmissible.Thus,onlyrelabeloperationscancreateadmissi
bleedges.Afteravertexuisrelabeled,however,Lemma26.28statesthatthere
arenoadmissibleedgesenteringubuttheremaybeadmissibleedgesleavingu.
Thus,bymovingutothefrontofL,thealgorithmensuresthatanyadmissible
edgesleavingusatisfythetopologicalsortordering.

Pgina179

758 Chapter26MaximumFlow

ToseethatnovertexprecedinguinLhasexcessflow,wedenotethevertex
thatwillbeuinthenextiterationbyu0.Theverticesthatwillprecedeu0inthe
nextiterationincludethecurrentu(duetoline11)andeithernoothervertices
(ifuisrelabeled)orthesameverticesasbefore(ifuisnotrelabeled).Whenu
isdischarged,ithasnoexcessflowafterward.Thus,ifuisrelabeledduring
thedischarge,noverticesprecedingu0haveexcessflow.Ifuisnotrelabeled
duringthedischarge,noverticesbeforeitonthelistacquiredexcessflowduring
thisdischarge,becauseLremainedtopologicallysortedatalltimesduringthe
discharge(asjustpointedout,admissibleedgesarecreatedonlybyrelabeling,
notpushing),andsoeachpushoperationcausesexcessflowtomoveonlyto
verticesfurtherdownthelist(ortosort).Again,noverticesprecedingu0have
excessflow.
Termination:Whentheloopterminates,uisjustpasttheendofL,andsothe
loopinvariantensuresthattheexcessofeveryvertexis0.Thus,nobasicoper
ationsapply.

Anlisis
WeshallnowshowthatRELABELTOFRONTrunsinOV3/timeonanyflow
networkGD.VE/.Sincethealgorithmisanimplementationofthegeneric
pushrelabelalgorithm,weshalltakeadvantageofCorollary26.21,whichpro
videsanOV/boundonthenumberofrelabeloperationsexecutedpervertexand
anOV2/boundonthetotalnumberofrelabeloperationsoverall.Inaddition,Ex
ercise26.43providesanO.VE/boundonthetotaltimespentperformingrelabel
operations,andLemma26.22providesanO.VE/boundonthetotalnumberof
saturatingpushoperations.

Theorem26.30
TherunningtimeofRELABELTOFRONTonanyflownetworkGD.VE/
isOV3/.

ProofLetusconsideraphaseoftherelabeltofrontalgorithmtobethetime
betweentwoconsecutiverelabeloperations.ThereareOV2/phases,sincethere
areOV2/relabeloperations.EachphaseconsistsofatmostjVjcallstoDIS
CHARGE,whichwecanseeasfollows.IfDISCHARGEdoesnotperformare
labeloperation,thenthenextcalltoDISCHARGEisfurtherdownthelistL,and
thelengthofLislessthanjVj.IfDISCHARGEdoesperformarelabel,thenext
calltoDISCHARGEbelongstoadifferentphase.Sinceeachphasecontainsat

https://translate.googleusercontent.com/translate_f 111/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
mostjVjcallstoDISCHARGEandthereareOV2/phases,thenumberoftimes
DISCHARGEiscalledinline8ofRELABELTOFRONTisOV3/.Thus,thetotal

Pgina180

26.5Therelabeltofrontalgorithm 759

workperformedbythewhileloopinRELABELTOFRONT,excludingthework
performedwithinDISCHARGE,isatmostOV3/.
WemustnowboundtheworkperformedwithinDISCHARGEduringtheex
ecutionofthealgorithm.EachiterationofthewhileloopwithinDISCHARGE
performsoneofthreeactions.Weshallanalyzethetotalamountofworkinvolved
inperformingeachoftheseactions.
Westartwithrelabeloperations(lines45).Exercise26.43providesanO.VE/
timeboundonalltheOV2/relabelsthatareperformed.
Now,supposethattheactionupdatestheu:currentpointerinline8.Thisaction
occursO.degree.u//timeseachtimeavertexuisrelabeled,andOVdegree.u//
timesoverallforthevertex.Forallvertices,therefore,thetotalamountofwork
doneinadvancingpointersinneighborlistsisO.VE/bythehandshakinglemma
(ExerciseB.41).
ThethirdtypeofactionperformedbyDISCHARGEisapushoperation(line7).
WealreadyknowthatthetotalnumberofsaturatingpushoperationsisO.VE/.
Observethatifanonsaturatingpushisexecuted,DISCHARGEimmediatelyreturns,
sincethepushreducestheexcessto0.Thus,therecanbeatmostonenonsaturating
pushpercalltoDISCHARGE.Aswehaveobserved,DISCHARGEiscalledOV3/
times,andthusthetotaltimespentperformingnonsaturatingpushesisOV3/.
TherunningtimeofRELABELTOFRONTisthereforeOV3CVE/,which
isOV3/.

Exercises

26.51
IllustratetheexecutionofRELABELTOFRONTinthemannerofFigure26.10for
theflownetworkinFigure26.1(a).AssumethattheinitialorderingofverticesinL
ish1234iandthattheneighborlistsare

1:NDhs23i
2:NDhs134i
3:NDh124ti
4:NDh23ti:

26.52?
Wewouldliketoimplementapushrelabelalgorithminwhichwemaintainafirst
in,firstoutqueueofoverflowingvertices.Thealgorithmrepeatedlydischargesthe
vertexattheheadofthequeue,andanyverticesthatwerenotoverflowingbefore
thedischargebutareoverflowingafterwardareplacedattheendofthequeue.
Afterthevertexattheheadofthequeueisdischarged,itisremoved.Cuandoel

Pgina181

760 Chapter26MaximumFlow

queueisempty,thealgorithmterminates.Showhowtoimplementthisalgorithm
tocomputeamaximumflowinOV3/time.

26.53
ShowthatthegenericalgorithmstillworksifRELABELupdatesu:hbysim
plycomputingu:hDu:hC1.Howwouldthischangeaffecttheanalysisof
RELABELTOFRONT?

26.54?
Showthatifwealwaysdischargeahighestoverflowingvertex,wecanmakethe
pushrelabelmethodruninOV3/time.

26.55
Supposethatatsomepointintheexecutionofapushrelabelalgorithm,thereexists
aninteger0<kjVj1forwhichnovertexhas:hDk.Showthatall
verticeswith:h>kareonthesourcesideofaminimumcut.Ifsuchakexists,
thegapheuristicupdateseveryvertex 2V fsgforwhich:h>k,toset
:hDmax.:hjVjC1/.Showthattheresultingattributehisaheightfunction.
(Thegapheuristiciscrucialinmakingimplementationsofthepushrelabelmethod

https://translate.googleusercontent.com/translate_f 112/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
performwellinpractice.)

Problemas

261Escapeproblem
Annngridisanundirectedgraphconsistingofnrowsandncolumnsofvertices,
asshowninFigure26.11.Wedenotethevertexintheithrowandthejthcolumn
by.ij/.Allverticesinagridhaveexactlyfourneighbors,exceptfortheboundary
vertices,whicharethepoints.ij/forwhichiD1,iDn,jD1,orjDn.
Givenmn2startingpoints.x1y1/.x2y2/:::.xmym/inthegrid,the
escapeproblemistodeterminewhetherornottherearemvertexdisjointpaths
fromthestartingpointstoanymdifferentpointsontheboundary.Porejemplo,
thegridinFigure26.11(a)hasanescape,butthegridinFigure26.11(b)doesnot.

a.Consideraflownetworkinwhichvertices,aswellasedges,havecapacities.
Thatis,thetotalpositiveflowenteringanygivenvertexissubjecttoacapacity
constraint.Showthatdeterminingthemaximumflowinanetworkwithedge
andvertexcapacitiescanbereducedtoanordinarymaximumflowproblemon
aflownetworkofcomparablesize.

Pgina182

ProblemsforChapter26 761

(un) (segundo)

Figure26.11Gridsfortheescapeproblem.Startingpointsareblack,andothergridverticesare
white.(a)Agridwithanescape,shownbyshadedpaths.(b)Agridwithnoescape.

segundo.Describeanefficientalgorithmtosolvetheescapeproblem,andanalyzeits
runningtime.

262Minimumpathcover
ApathcoverofadirectedgraphGD.VE/isasetPofvertexdisjointpaths
suchthateveryvertexinVisincludedinexactlyonepathinP.Pathsmaystart
andendanywhere,andtheymaybeofanylength,including0.Aminimumpath
coverofGisapathcovercontainingthefewestpossiblepaths.
a.Giveanefficientalgorithmtofindaminimumpathcoverofadirectedacyclic
graphGD.VE/.(Hint:AssumingthatVDf12:::ng,constructthe
graphG0D.V0E0/,where
V0 Dfx0x1:::xng[fy0y1:::yng
E0 Dfx0xi/Wi2Vg[fyiy0/Wi2Vg[fxiyj/W.ij/2Eg
andrunamaximumflowalgorithm.)

segundo.Doesyouralgorithmworkfordirectedgraphsthatcontaincycles?Explique.

263Algorithmicconsulting
ProfessorGorewantstoopenupanalgorithmicconsultingcompany.Hehasiden
tifiednimportantsubareasofalgorithms(roughlycorrespondingtodifferentpor
tionsofthistextbook),whichherepresentsbythesetADfA1A2:::Ang.En
eachsubareaAk,hecanhireanexpertinthatareaforckdollars.Theconsulting
companyhaslinedupasetJDfJ1J2:::Jmgofpotentialjobs.Afindeque
performjobJi,thecompanyneedstohavehiredexpertsinasubsetRiAof

Pgina183

762 Chapter26MaximumFlow

https://translate.googleusercontent.com/translate_f 113/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

subareas.Eachexpertcanworkonmultiplejobssimultaneously.Ifthecompany
choosestoacceptjobJi,itmusthavehiredexpertsinallsubareasinRi,anditwill
takeinrevenueofpidollars.
ProfessorGore'sjobistodeterminewhichsubareastohireexpertsinandwhich
jobstoacceptinordertomaximizethenetrevenue,whichisthetotalincomefrom
jobsacceptedminusthetotalcostofemployingtheexperts.
ConsiderthefollowingflownetworkG.Itcontainsasourcevertexs,vertices
A1A2:::An,verticesJ1J2:::Jm,andasinkvertext.ForkD12:::n,
theflownetworkcontainsanedge.sAk/withcapacitycsAk/Dck,and
foriD12:::m,theflownetworkcontainsanedge.Jit/withcapacity
cJit/Dpi.ForkD12:::nandiD12:::m,ifAk2Ri,thenG
containsanedge.AkJi/withcapacitycAkJi/D1.

a.ShowthatifJi2Tforafinitecapacitycut.ST/ofG,thenAk2Tforeach
Ak2Ri.

segundo.Showhowtodeterminethemaximumnetrevenuefromthecapacityofamini
mumcutofGandthegivenpivalues.

do.Giveanefficientalgorithmtodeterminewhichjobstoacceptandwhichexperts
tohire.Analyzetherunningtimeofyouralgorithmintermsofm,n,and
Pm
Rd iD1jRij.

264Updatingmaximumflow
LetGD.VE/beaflownetworkwithsources,sinkt,andintegercapacities.
SupposethatwearegivenamaximumflowinG.

a.Supposethatweincreasethecapacityofasingleedge.u/2Eby1.Give
anOVCE/timealgorithmtoupdatethemaximumflow.

segundo.Supposethatwedecreasethecapacityofasingleedge.u/2Eby1.Give
anOVCE/timealgorithmtoupdatethemaximumflow.

265Maximumflowbyscaling
LetGD.VE/beaflownetworkwithsources,sinkt,andanintegercapac
itycu/oneachedge.u/2E.LetCDmax.u/2Ecu/.

a.ArguethataminimumcutofGhascapacityatmostCjEj.

segundo.ForagivennumberK,showhowtofindanaugmentingpathofcapacityat
leastKinOE/time,ifsuchapathexists.

Page184

ProblemsforChapter26 763

WecanusethefollowingmodificationofFORDFULKERSONMETHODtocom
puteamaximumflowinG:

MAXFLOWBYSCALING.Gst/
1CDmax.u/2Ecu/
2initializeflowfto0
3KD2blgCc
4whileK 1
5 whilethereexistsanaugmentingpathpofcapacityatleastK
6 augmentflowfalongp
7 KDK=2
8returnf

do.ArguethatMAXFLOWBYSCALINGreturnsamaximumflow.

re.ShowthatthecapacityofaminimumcutoftheresidualnetworkGfisatmost
2KjEjeachtimeline4isexecuted.

mi.Arguethattheinnerwhileloopoflines56executesOE/timesforeachvalue
ofK.

f.ConcludethatMAXFLOWBYSCALINGcanbeimplementedsothatitruns
inOE2lgC/time.

266TheHopcroftKarpbipartitematchingalgorithm
Inthisproblem,wedescribeafasteralgorithm,duetoHopcroftandKarp,forpag
findingamaximummatchinginabipartitegraph.ThealgorithmrunsinO. VE/
hora.Givenanundirected,bipartitegraphGD.VE/,whereVDL[Rand
alledgeshaveexactlyoneendpointinL,letMbeamatchinginG.Wesaythat
asimplepathPinGisanaugmentingpathwithrespecttoMifitstartsatan

https://translate.googleusercontent.com/translate_f 114/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
unmatchedvertexinL,endsatanunmatchedvertexinR,anditsedgesbelong
alternatelytoMandE M.(Thisdefinitionofanaugmentingpathisrelated
to,butdifferentfrom,anaugmentingpathinaflownetwork.)Inthisproblem,
wetreatapathasasequenceofedges,ratherthanasasequenceofvertices.UN
shortestaugmentingpathwithrespecttoamatchingMisanaugmentingpath
withaminimumnumberofedges.
GiventwosetsAandB,thesymmetricdifferenceABisdefinedas.AB/[
.BA/,thatis,theelementsthatareinexactlyoneofthetwosets.

Pgina185

764 Chapter26MaximumFlow

a.ShowthatifMisamatchingandPisanaugmentingpathwithrespecttoM,
thenthesymmetricdifferenceMPisamatchingandjMPjDjMjC1.
ShowthatifP1P2:::Pkarevertexdisjointaugmentingpathswithrespect
toM,thenthesymmetricdifferenceM.P1[P2[[Pk/isamatching
withcardinalityjMjCk.

Thegeneralstructureofouralgorithmisthefollowing:

HOPCROFTKARP.G/
1MD
2repeat
3 letPDfP1P2:::Pkgbeamaximalsetofvertexdisjoint
shortestaugmentingpathswithrespecttoM
4 MDM.P1[P2[[Pk/
5untilP==
6returnM

Theremainderofthisproblemasksyoutoanalyzethenumberofiterationsin
thealgorithm(thatis,thenumberofiterationsintherepeatloop)andtodescribe
animplementationofline3.

segundo.GiventwomatchingsMandMinG,showthateveryvertexinthegraph
G0D.VMM/hasdegreeatmost2.ConcludethatG0isadisjoint
unionofsimplepathsorcycles.Arguethatedgesineachsuchsimplepath
orcyclebelongalternatelytoMorM.ProvethatifjMjjMj,then
MMcontainsatleastjMjjMjvertexdisjointaugmentingpathswith
respecttoM.

LetlbethelengthofashortestaugmentingpathwithrespecttoamatchingM,and
letP1P2:::Pkbeamaximalsetofvertexdisjointaugmentingpathsoflengthl
withrespecttoM.LetM0DM.P1[[Pk/,andsupposethatPisashortest
augmentingpathwithrespecttoM0.

do.ShowthatifPisvertexdisjointfromP1P2:::Pk,thenPhasmorethanl
edges.

re.NowsupposethatPisnotvertexdisjointfromP1P2:::Pk.LetAbethe
setofedges.MM0/P.ShowthatAD.P1[P2[[Pk/Pand
thatjAj.kC1/l.ConcludethatPhasmorethanledges.

mi.ProvethatifashortestaugmentingpathwithrespecttoMhasledges,thesize
ofthemaximummatchingisatmostjMjCjVj=.lC1/.

Page186

NotesforChapter26 765

f.Showthatthenumberofrepeatloopiterationsinthealgorithmisat
pag pag
most2 jVj.(Hint:ByhowmuchcanMgrowafteriterationnumber jVj?)

g.GiveanalgorithmthatrunsinOE/timetofindamaximalsetofvertex
disjointshortestaugmentingpathsP1P2:::PkforagivenmatchingM.
pag
ConcludethatthetotalrunningtimeofHOPCROFTKARPisO. VE/.

Chapternotes

https://translate.googleusercontent.com/translate_f 115/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Ahuja,Magnanti,andOrlin[7],Even[103],Lawler[224],PapadimitriouandStei
glitz[271],andTarjan[330]aregoodreferencesfornetworkflowandrelatedalgo
rithms.Goldberg,Tardos,andTarjan[139]alsoprovideanicesurveyofalgorithms
fornetworkflowproblems,andSchrijver[304]haswrittenaninterestingreview
ofhistoricaldevelopmentsinthefieldofnetworkflows.
TheFordFulkersonmethodisduetoFordandFulkerson[109],whooriginated
theformalstudyofmanyoftheproblemsintheareaofnetworkflow,including
themaximumflowandbipartitematchingproblems.Manyearlyimplementations
oftheFordFulkersonmethodfoundaugmentingpathsusingbreadthfirstsearch
EdmondsandKarp[102],andindependentlyDinic[89],provedthatthisstrategy
yieldsapolynomialtimealgorithm.Arelatedidea,thatofusingblockingflows,
wasalsofirstdevelopedbyDinic[89].Karzanov[202]firstdevelopedtheideaof
preflows.ThepushrelabelmethodisduetoGoldberg[136]andGoldbergandTar
jan[140].GoldbergandTarjangaveanOV3/timealgorithmthatusesaqueueto
maintainthesetofoverflowingvertices,aswellasanalgorithmthatusesdynamic
treestoachievearunningtimeofO.VElg.V2=EC2//.Severalotherresearchers
havedevelopedpushrelabelmaximumflowalgorithms.AhujaandOrlin[9]and
Ahuja,Orlin,andTarjan[10]gavealgorithmsthatusedscaling.Cheriyanand
Maheshwari[62]proposedpushingflowfromtheoverflowingvertexofmaximum
altura.CheriyanandHagerup[61]suggestedrandomlypermutingtheneighbor
lists,andseveralresearchers[14,204,276]developedcleverderandomizationsof
thisidea,leadingtoasequenceoffasteralgorithms.ThealgorithmofKing,Rao,
andTarjan[204]isthefastestsuchalgorithmandrunsinO.VElogE=.VlgV/V/
hora.
Theasymptoticallyfastestalgorithmtodateforthemaximumflowproblem,by
GoldbergandRao[138],runsintimeO.min.V2=3E1=2/Elg.V2=EC2/lgC/,
whereCDmax.u/2Ecu/.Thisalgorithmdoesnotusethepushrelabel
methodbutinsteadisbasedonfindingblockingflows.Allpreviousmaximum
flowalgorithms,includingtheonesinthischapter,usesomenotionofdistance
(thepushrelabelalgorithmsusetheanalogousnotionofheight),withalengthof1

Page187

766 Chapter26MaximumFlow

assignedimplicitlytoeachedge.Thisnewalgorithmtakesadifferentapproachand
assignsalengthof0tohighcapacityedgesandalengthof1tolowcapacityedges.
Informally,withrespecttotheselengths,shortestpathsfromthesourcetothesink
tendhavehighcapacity,whichmeansthatfeweriterationsneedbeperformed.
Inpractice,pushrelabelalgorithmscurrentlydominateaugmentingpathor
linearprogrammingbasedalgorithmsforthemaximumflowproblem.Unestudio
byCherkasskyandGoldberg[63]underscorestheimportanceofusingtwoheuris
ticswhenimplementingapushrelabelalgorithm.Thefirstheuristicistoperi
odicallyperformabreadthfirstsearchoftheresidualnetworkinordertoobtain
moreaccurateheightvalues.Thesecondheuristicisthegapheuristic,describedin
Exercise26.55.CherkasskyandGoldbergconcludethatthebestchoiceofpush
relabelvariantsistheonethatchoosestodischargetheoverflowingvertexwiththe
maximumheight.
Thebestalgorithmtodateformaximumbipartitematching,discoveredby
pag
HopcroftandKarp[176],runsinO. VE/timeandisdescribedinProblem266.
ThebookbyLovszandPlummer[239]isanexcellentreferenceonmatching
problemas.

https://translate.googleusercontent.com/translate_f 116/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina189
Pgina188

VIISelectedTopics

Pgina190

Introduccin

Thispartcontainsaselectionofalgorithmictopicsthatextendandcomplement
earliermaterialinthisbook.Somechaptersintroducenewmodelsofcomputation
suchascircuitsorparallelcomputers.Otherscoverspecializeddomainssuchas
computationalgeometryornumbertheory.Thelasttwochaptersdiscusssomeof
theknownlimitationstothedesignofefficientalgorithmsandintroducetechniques

https://translate.googleusercontent.com/translate_f 117/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
forcopingwiththoselimitations.
Chapter27presentsanalgorithmicmodelforparallelcomputingbasedondy
namicmultithreading.Thechapterintroducesthebasicsofthemodel,showing
howtoquantifyparallelismintermsofthemeasuresofworkandspan.Entonces
investigatesseveralinterestingmultithreadedalgorithms,includingalgorithmsfor
matrixmultiplicationandmergesorting.
Chapter28studiesefficientalgorithmsforoperatingonmatrices.Itpresents
twogeneralmethodsLUdecompositionandLUPdecompositionforsolving
linearequationsbyGaussianeliminationinOn3/time.Italsoshowsthatmatrix
inversionandmatrixmultiplicationcanbeperformedequallyfast.Thechapter
concludesbyshowinghowtocomputealeastsquaresapproximatesolutionwhen
asetoflinearequationshasnoexactsolution.
Chapter29studieslinearprogramming,inwhichwewishtomaximizeormini
mizeanobjective,givenlimitedresourcesandcompetingconstraints.Linearpro
grammingarisesinavarietyofpracticalapplicationareas.Thischaptercovershow
toformulateandsolvelinearprograms.Thesolutionmethodcoveredisthesim
plexalgorithm,whichistheoldestalgorithmforlinearprogramming.Adiferenciade
tomanyalgorithmsinthisbook,thesimplexalgorithmdoesnotruninpolynomial
timeintheworstcase,butitisfairlyefficientandwidelyusedinpractice.

Pgina191

770 PartVIISelectedTopics

Chapter30studiesoperationsonpolynomialsandshowshowtouseawell
knownsignalprocessingtechniquethefastFouriertransform(FFT)tomulti
plytwodegreenpolynomialsinO.nlgn/time.Italsoinvestigatesefficientim
plementationsoftheFFT,includingaparallelcircuit.
Chapter31presentsnumbertheoreticalgorithms.Afterreviewingelementary
numbertheory,itpresentsEuclid'salgorithmforcomputinggreatestcommondi
visors.Next,itstudiesalgorithmsforsolvingmodularlinearequationsandfor
raisingonenumbertoapowermoduloanothernumber.Then,itexploresanimpor
tantapplicationofnumbertheoreticalgorithms:theRSApublickeycryptosystem.
Thiscryptosystemcanbeusednotonlytoencryptmessagessothatanadversary
cannotreadthem,butalsotoprovidedigitalsignatures.Thechapterthenpresents
theMillerRabinrandomizedprimalitytest,withwhichwecanfindlargeprimes
efficientlyanessentialrequirementfortheRSAsystem.Finally,thechaptercov
ersPollard'srhoheuristicforfactoringintegersanddiscussesthestateoftheart
ofintegerfactorization.
Chapter32studiestheproblemoffindingalloccurrencesofagivenpattern
stringinagiventextstring,aproblemthatarisesfrequentlyintexteditingpro
GramosAfterexaminingthenaiveapproach,thechapterpresentsanelegantap
proachduetoRabinandKarp.Then,aftershowinganefficientsolutionbased
onfiniteautomata,thechapterpresentstheKnuthMorrisPrattalgorithm,which
modifiestheautomatonbasedalgorithmtosavespacebycleverlypreprocessing
thepattern.
Chapter33considersafewproblemsincomputationalgeometry.Afterdis
cussingbasicprimitivesofcomputationalgeometry,thechaptershowshowtouse
asweepingmethodtoefficientlydeterminewhetherasetoflinesegmentscon
tainsanyintersections.Twocleveralgorithmsforfindingtheconvexhullofasetof
pointsGraham'sscanandJarvis'smarchalsoillustratethepowerofsweeping
Mtodos.Thechaptercloseswithanefficientalgorithmforfindingtheclosestpair
fromamongagivensetofpointsintheplane.
Chapter34concernsNPcompleteproblems.Manyinterestingcomputational
problemsareNPcomplete,butnopolynomialtimealgorithmisknownforsolving
anyofthem.Thischapterpresentstechniquesfordeterminingwhenaproblemis
NPcomplete.SeveralclassicproblemsareprovedtobeNPcomplete:determining
whetheragraphhasahamiltoniancycle,determiningwhetherabooleanformula
issatisfiable,anddeterminingwhetheragivensetofnumbershasasubsetthat
addsuptoagiventargetvalue.Thechapteralsoprovesthatthefamoustraveling
salesmanproblemisNPcomplete.
Chapter35showshowtofindapproximatesolutionstoNPcompleteproblems
efficientlybyusingapproximationalgorithms.ForsomeNPcompleteproblems,
approximatesolutionsthatarenearoptimalarequiteeasytoproduce,butforothers
eventhebestapproximationalgorithmsknownworkprogressivelymorepoorlyas

Pgina192

PartVIISelectedTopics 771

theproblemsizeincreases.Then,therearesomeproblemsforwhichwecaninvest
increasingamountsofcomputationtimeinreturnforincreasinglybetterapprox
imatesolutions.Thischapterillustratesthesepossibilitieswiththevertexcover
https://translate.googleusercontent.com/translate_f 118/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
problem(unweightedandweightedversions),anoptimizationversionof3CNF
satisfiability,thetravelingsalesmanproblem,thesetcoveringproblem,andthe
subsetsumproblem.

Pgina193

27 MultithreadedAlgorithms

Thevastmajorityofalgorithmsinthisbookareserialalgorithmssuitablefor
runningonauniprocessorcomputerinwhichonlyoneinstructionexecutesata
hora.Inthischapter,weshallextendouralgorithmicmodeltoencompassparallel
algorithms,whichcanrunonamultiprocessorcomputerthatpermitsmultiple
instructionstoexecuteconcurrently.Inparticular,weshallexploretheelegant
modelofdynamicmultithreadedalgorithms,whichareamenabletoalgorithmic
designandanalysis,aswellastoefficientimplementationinpractice.
Parallelcomputerscomputerswithmultipleprocessingunitshavebecome
increasinglycommon,andtheyspanawiderangeofpricesandperformance.Rela
tivelyinexpensivedesktopandlaptopchipmultiprocessorscontainasinglemulti
coreintegratedcircuitchipthathousesmultipleprocessingcores,eachofwhich
isafullfledgedprocessorthatcanaccessacommonmemory.Atanintermedi
ateprice/performancepointareclustersbuiltfromindividualcomputersoften
simplePCclassmachineswithadedicatednetworkinterconnectingthem.los
highestpricedmachinesaresupercomputers,whichoftenuseacombinationof
customarchitecturesandcustomnetworkstodeliverthehighestperformancein
termsofinstructionsexecutedpersecond.
Multiprocessorcomputershavebeenaround,inoneformoranother,for
Dcadas.Althoughthecomputingcommunitysettledontherandomaccessma
chinemodelforserialcomputingearlyoninthehistoryofcomputerscience,no
singlemodelforparallelcomputinghasgainedaswideacceptance.Amajorrea
sonisthatvendorshavenotagreedonasinglearchitecturalmodelforparallel

https://translate.googleusercontent.com/translate_f 119/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
computers.Forexample,someparallelcomputersfeaturesharedmemory,where
eachprocessorcandirectlyaccessanylocationofmemory.Otherparallelcom
putersemploydistributedmemory,whereeachprocessor'smemoryisprivate,and
anexplicitmessagemustbesentbetweenprocessorsinorderforoneprocessorto
accessthememoryofanother.Withtheadventofmulticoretechnology,however,
everynewlaptopanddesktopmachineisnowasharedmemoryparallelcomputer,

Pgina194

Chapter27MultithreadedAlgorithms 773

andthetrendappearstobetowardsharedmemorymultiprocessing.Althoughtime
willtell,thatistheapproachweshalltakeinthischapter.
Onecommonmeansofprogrammingchipmultiprocessorsandothershared
memoryparallelcomputersisbyusingstaticthreading,whichprovidesasoftware
abstractionofvirtualprocessors,orthreads,sharingacommonmemory.Cada
threadmaintainsanassociatedprogramcounterandcanexecutecodeindepen
dentlyoftheotherthreads.Theoperatingsystemloadsathreadontoaprocessor
forexecutionandswitchesitoutwhenanotherthreadneedstorun.Aunqueel
operatingsystemallowsprogrammerstocreateanddestroythreads,theseopera
tionsarecomparativelyslow.Thus,formostapplications,threadspersistforthe
durationofacomputation,whichiswhywecallthemstatic.
Unfortunately,programmingasharedmemoryparallelcomputerdirectlyusing
staticthreadsisdifficultanderrorprone.Onereasonisthatdynamicallyparti
tioningtheworkamongthethreadssothateachthreadreceivesapproximately
thesameloadturnsouttobeacomplicatedundertaking.Foranybutthesim
plestofapplications,theprogrammermustusecomplexcommunicationprotocols
toimplementaschedulertoloadbalancethework.Thisstateofaffairshasled
towardthecreationofconcurrencyplatforms,whichprovidealayerofsoftware
thatcoordinates,schedules,andmanagestheparallelcomputingresources.Algunos
concurrencyplatformsarebuiltasruntimelibraries,butothersprovidefullfledged
parallellanguageswithcompilerandruntimesupport.

Dynamicmultithreadedprogramming
Oneimportantclassofconcurrencyplatformisdynamicmultithreading,whichis
themodelweshalladoptinthischapter.Dynamicmultithreadingallowsprogram
merstospecifyparallelisminapplicationswithoutworryingaboutcommunication
protocols,loadbalancing,andothervagariesofstaticthreadprogramming.los
concurrencyplatformcontainsascheduler,whichloadbalancesthecomputation
automatically,therebygreatlysimplifyingtheprogrammer'schore.Aunqueel
functionalityofdynamicmultithreadingenvironmentsisstillevolving,almostall
supporttwofeatures:nestedparallelismandparallelloops.Nestedparallelism
allowsasubroutinetobespawned,allowingthecallertoproceedwhilethe
spawnedsubroutineiscomputingitsresult.Aparallelloopislikeanordinary
forloop,exceptthattheiterationsoftheloopcanexecuteconcurrently.
Thesetwofeaturesformthebasisofthemodelfordynamicmultithreadingthat
weshallstudyinthischapter.Akeyaspectofthismodelisthattheprogrammer
needstospecifyonlythelogicalparallelismwithinacomputation,andthethreads
withintheunderlyingconcurrencyplatformscheduleandloadbalancethecompu
tationamongthemselves.Weshallinvestigatemultithreadedalgorithmswrittenfor

Pgina195

774 Chapter27MultithreadedAlgorithms

thismodel,aswellhowtheunderlyingconcurrencyplatformcanschedulecompu
tationsefficiently.
Ourmodelfordynamicmultithreadingoffersseveralimportantadvantages:
Itisasimpleextensionofourserialprogrammingmodel.Wecandescribea
multithreadedalgorithmbyaddingtoourpseudocodejustthreeconcurrency
keywords:parallel,spawn,andsync.Moreover,ifwedeletetheseconcur
rencykeywordsfromthemultithreadedpseudocode,theresultingtextisserial
pseudocodeforthesameproblem,whichwecalltheserializationofthemul
tithreadedalgorithm.
Itprovidesatheoreticallycleanwaytoquantifyparallelismbasedontheno
tionsofworkandspan.
Manymultithreadedalgorithmsinvolvingnestedparallelismfollownaturally

https://translate.googleusercontent.com/translate_f 120/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
fromthedivideandconquerparadigm.Moreover,justasserialdivideand
conqueralgorithmslendthemselvestoanalysisbysolvingrecurrences,sodo
multithreadedalgorithms.
Themodelisfaithfultohowparallelcomputingpracticeisevolving.Agrow
ingnumberofconcurrencyplatformssupportonevariantoranotherofdynamic
multithreading,includingCilk[51,118],Cilk++[71],OpenMP[59],TaskPar
allelLibrary[230],andThreadingBuildingBlocks[292].
Section27.1introducesthedynamicmultithreadingmodelandpresentsthemet
ricsofwork,span,andparallelism,whichweshallusetoanalyzemultithreaded
AlgoritmosSection27.2investigateshowtomultiplymatriceswithmultithread
ing,andSection27.3tacklesthetougherproblemofmultithreadingmergesort.

27.1Thebasicsofdynamicmultithreading

Weshallbeginourexplorationofdynamicmultithreadingusingtheexampleof
computingFibonaccinumbersrecursively.RecallthattheFibonaccinumbersare
definedbyrecurrence(3.22):
F0 D0
F1 D1
Fi DFi1CFi2 fori 2:

Hereisasimple,recursive,serialalgorithmtocomputethenthFibonaccinumber:

Page196

27.1Thebasicsofdynamicmultithreading 775

FIB.6/

FIB.5/ FIB.4/

FIB.4/ FIB.3/ FIB.3/ FIB.2/

FIB.3/ FIB.2/ FIB.2/ FIB.1/ FIB.2/ FIB.1/ FIB.1/ FIB.0/

FIB.2/ FIB.1/ FIB.1/ FIB.0/ FIB.1/ FIB.0/ FIB.1/ FIB.0/

FIB.1/ FIB.0/

Figure27.1ThetreeofrecursiveprocedureinstanceswhencomputingFIB.6/.Eachinstanceof
FIBwiththesameargumentdoesthesameworktoproducethesameresult,providinganinefficient
butinterestingwaytocomputeFibonaccinumbers.

FIB.n/
1ifn1
2 returnn
3elsexDFIB.n1/
4 yDFIB.n2/
5 returnxCy

YouwouldnotreallywanttocomputelargeFibonaccinumbersthisway,be
causethiscomputationdoesmuchrepeatedwork.Figure27.1showsthetreeof
recursiveprocedureinstancesthatarecreatedwhencomputingF6.Porejemplo,
acalltoFIB.6/recursivelycallsFIB.5/andthenFIB.4/.But,thecalltoFIB.5/
alsoresultsinacalltoFIB.4/.BothinstancesofFIB.4/returnthesameresult
(F4D3).SincetheFIBproceduredoesnotmemoize,thesecondcalltoFIB.4/
replicatestheworkthatthefirstcallperforms.
LetT.n/denotetherunningtimeofFIB.n/.SinceFIB.n/containstworecur
sivecallsplusaconstantamountofextrawork,weobtaintherecurrence
T.n/DT.n1/CT.n2/C.1/:
ThisrecurrencehassolutionT.n/D.Fn/,whichwecanshowusingthesubsti
tutionmethod.Foraninductivehypothesis,assumethatT.n/aFn b,where
a>1andb>0areconstants.Substituting,weobtain

https://translate.googleusercontent.com/translate_f 121/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Pgina197

776 Chapter27MultithreadedAlgorithms

T.n/.aFn1 b/C.aFn2 b/C.1/


DaFn1CFn2/2bC.1/
DaFn b.b.1//
aFn segundo
ifwechooseblargeenoughtodominatetheconstantinthe.1/.Wecanthen
choosealargeenoughtosatisfytheinitialcondition.Theanalyticalbound
T.n/D.n/ (27.1)
pag
dnde D.1C 5/=2isthegoldenratio,nowfollowsfromequation(3.25).
SinceFngrowsexponentiallyinn,thisprocedureisaparticularlyslowwayto
computeFibonaccinumbers.(SeeProblem313formuchfasterways.)
AlthoughtheFIBprocedureisapoorwaytocomputeFibonaccinumbers,it
makesagoodexampleforillustratingkeyconceptsintheanalysisofmultithreaded
AlgoritmosObservethatwithinFIB.n/,thetworecursivecallsinlines3and4to
FIB.n1/andFIB.n2/,respectively,areindependentofeachother:theycould
becalledineitherorder,andthecomputationperformedbyoneinnowayaffects
elotro.Therefore,thetworecursivecallscanruninparallel.
Weaugmentourpseudocodetoindicateparallelismbyaddingtheconcurrency
keywordsspawnandsync.HereishowwecanrewritetheFIBproceduretouse
dynamicmultithreading:

PFIB.n/
1ifn1
2 returnn
3elsexDspawnPFIB.n1/
4 yDPFIB.n2/
5 sync
6 returnxCy

NoticethatifwedeletetheconcurrencykeywordsspawnandsyncfromPFIB,
theresultingpseudocodetextisidenticaltoFIB(otherthanrenamingtheprocedure
intheheaderandinthetworecursivecalls).Wedefinetheserializationofamul
tithreadedalgorithmtobetheserialalgorithmthatresultsfromdeletingthemulti
threadedkeywords:spawn,sync,andwhenweexamineparallelloops,parallel.
Indeed,ourmultithreadedpseudocodehasthenicepropertythataserializationis
alwaysordinaryserialpseudocodetosolvethesameproblem.
Nestedparallelismoccurswhenthekeywordspawnprecedesaprocedurecall,
asinline3.Thesemanticsofaspawndiffersfromanordinaryprocedurecallin
thattheprocedureinstancethatexecutesthespawntheparentmaycontinue
toexecuteinparallelwiththespawnedsubroutineitschildinsteadofwaiting

Page198

27.1Thebasicsofdynamicmultithreading 777

forthechildtocomplete,aswouldnormallyhappeninaserialexecution.Enesto
case,whilethespawnedchildiscomputingPFIB.n1/,theparentmaygoon
tocomputePFIB.n2/inline4inparallelwiththespawnedchild.Desdeel
PFIBprocedureisrecursive,thesetwosubroutinecallsthemselvescreatenested
parallelism,asdotheirchildren,therebycreatingapotentiallyvasttreeofsubcom
putations,allexecutinginparallel.
Thekeywordspawndoesnotsay,however,thataproceduremustexecutecon
currentlywithitsspawnedchildren,onlythatitmay.Theconcurrencykeywords
expressthelogicalparallelismofthecomputation,indicatingwhichpartsofthe
computationmayproceedinparallel.Atruntime,itisuptoaschedulertodeter
minewhichsubcomputationsactuallyrunconcurrentlybyassigningthemtoavail
ableprocessorsasthecomputationunfolds.Weshalldiscussthetheorybehind
schedulersshortly.
Aprocedurecannotsafelyusethevaluesreturnedbyitsspawnedchildrenuntil
afteritexecutesasyncstatement,asinline5.Thekeywordsyncindicatesthat
theproceduremustwaitasnecessaryforallitsspawnedchildrentocompletebe
foreproceedingtothestatementafterthesync.InthePFIBprocedure,async
isrequiredbeforethereturnstatementinline6toavoidtheanomalythatwould
occurifxandyweresummedbeforexwascomputed.Inadditiontoexplicit
synchronizationprovidedbythesyncstatement,everyprocedureexecutesasync
implicitlybeforeitreturns,thusensuringthatallitschildrenterminatebeforeit
hace.

Amodelformultithreadedexecution

https://translate.googleusercontent.com/translate_f 122/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Ithelpstothinkofamultithreadedcomputationthesetofruntimeinstruc
tionsexecutedbyaprocessoronbehalfofamultithreadedprogramasadirected
acyclicgraphGD.VE/,calledacomputationdag.Asanexample,Figure27.2
showsthecomputationdagthatresultsfromcomputingPFIB.4/.Conceptually,
theverticesinVareinstructions,andtheedgesinErepresentdependenciesbe
tweeninstructions,where.u/2Emeansthatinstructionumustexecutebefore
instruction.Forconvenience,however,ifachainofinstructionscontainsno
parallelcontrol(nospawn,sync,orreturnfromaspawnviaeitheranexplicit
returnstatementorthereturnthathappensimplicitlyuponreachingtheendof
aprocedure),wemaygroupthemintoasinglestrand,eachofwhichrepresents
oneormoreinstructions.Instructionsinvolvingparallelcontrolarenotincluded
instrands,butarerepresentedinthestructureofthedag.Forexample,ifastrand
hastwosuccessors,oneofthemmusthavebeenspawned,andastrandwithmul
tiplepredecessorsindicatesthepredecessorsjoinedbecauseofasyncstatement.
Thus,inthegeneralcase,thesetVformsthesetofstrands,andthesetEofdi
rectededgesrepresentsdependenciesbetweenstrandsinducedbyparallelcontrol.

Pgina199

778 Chapter27MultithreadedAlgorithms

PFIB(4)

PFIB(3) PFIB(2)

PFIB(2) PFIB(1) PFIB(1) PFIB(0)

PFIB(1) PFIB(0)

Figure27.2AdirectedacyclicgraphrepresentingthecomputationofPFIB.4/.Eachcirclerep
resentsonestrand,withblackcirclesrepresentingeitherbasecasesorthepartoftheprocedure
(instance)uptothespawnofPFIB.n1/inline3,shadedcirclesrepresentingthepartofthepro
cedurethatcallsPFIB.n2/inline4uptothesyncinline5,whereitsuspendsuntilthespawnof
PFIB.n1/returns,andwhitecirclesrepresentingthepartoftheprocedureafterthesyncwhere
itsumsxandyuptothepointwhereitreturnstheresult.Eachgroupofstrandsbelongingtothe
sameprocedureissurroundedbyaroundedrectangle,lightlyshadedforspawnedproceduresand
heavilyshadedforcalledprocedures.Spawnedgesandcalledgespointdownward,continuation
edgespointhorizontallytotheright,andreturnedgespointupward.Assumingthateachstrandtakes
unittime,theworkequals17timeunits,sincethereare17strands,andthespanis8timeunits,since
thecriticalpathshownwithshadededgescontains8strands.

IfGhasadirectedpathfromstrandutostrand,wesaythatthetwostrandsare
(logically)inseries.Otherwise,strandsuandare(logically)inparallel.
Wecanpictureamultithreadedcomputationasadagofstrandsembeddedina
treeofprocedureinstances.Forexample,Figure27.1showsthetreeofprocedure
instancesforPFIB.6/withoutthedetailedstructureshowingstrands.Figure27.2
zoomsinonasectionofthattree,showingthestrandsthatconstituteeachproce
dure.Alldirectededgesconnectingstrandsruneitherwithinaprocedureoralong
undirectededgesintheproceduretree.
Wecanclassifytheedgesofacomputationdagtoindicatethekindofdependen
ciesbetweenthevariousstrands.Acontinuationedge.uu0/,drawnhorizontally
inFigure27.2,connectsastrandutoitssuccessoru0withinthesameprocedure
ejemplo.Whenastranduspawnsastrand,thedagcontainsaspawnedge.u/,
whichpointsdownwardinthefigure.Calledges,representingnormalprocedure
calls,alsopointdownward.Stranduspawningstranddiffersfromucalling
inthataspawninducesahorizontalcontinuationedgefromutothestrandu0fol

Pgina200

27.1Thebasicsofdynamicmultithreading 779

lowinguinitsprocedure,indicatingthatu0isfreetoexecuteatthesametime
as,whereasacallinducesnosuchedge.Whenastrandureturnstoitscalling
procedureandxisthestrandimmediatelyfollowingthenextsyncinthecalling
procedure,thecomputationdagcontainsreturnedge.ux/,whichpointsupward.
Acomputationstartswithasingleinitialstrandtheblackvertexintheprocedure
labeledPFIB.4/inFigure27.2andendswithasinglefinalstrandthewhite

https://translate.googleusercontent.com/translate_f 123/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
vertexintheprocedurelabeledPFIB.4/.
Weshallstudytheexecutionofmultithreadedalgorithmsonanidealparal
lelcomputer,whichconsistsofasetofprocessorsandasequentiallyconsistent
sharedmemory.Sequentialconsistencymeansthatthesharedmemory,whichmay
inrealitybeperformingmanyloadsandstoresfromtheprocessorsatthesame
time,producesthesameresultsasifateachstep,exactlyoneinstructionfromone
oftheprocessorsisexecuted.Thatis,thememorybehavesasiftheinstructions
wereexecutedsequentiallyaccordingtosomegloballinearorderthatpreservesthe
individualordersinwhicheachprocessorissuesitsowninstructions.Fordynamic
multithreadedcomputations,whicharescheduledontoprocessorsautomatically
bytheconcurrencyplatform,thesharedmemorybehavesasifthemultithreaded
computation'sinstructionswereinterleavedtoproducealinearorderthatpreserves
thepartialorderofthecomputationdag.Dependingonscheduling,theordering
coulddifferfromonerunoftheprogramtoanother,butthebehaviorofanyexe
cutioncanbeunderstoodbyassumingthattheinstructionsareexecutedinsome
linearorderconsistentwiththecomputationdag.
Inadditiontomakingassumptionsaboutsemantics,theidealparallelcomputer
modelmakessomeperformanceassumptions.Specifically,itassumesthateach
processorinthemachinehasequalcomputingpower,anditignoresthecostof
ProgramacinAlthoughthislastassumptionmaysoundoptimistic,itturnsoutthat
foralgorithmswithsufficientparallelism(atermweshalldefinepreciselyina
moment),theoverheadofschedulingisgenerallyminimalinpractice.

Medidasdedesempeo
Wecangaugethetheoreticalefficiencyofamultithreadedalgorithmbyusingtwo
metrics:workandspan.Theworkofamultithreadedcomputationisthetotal
timetoexecutetheentirecomputationononeprocessor.Inotherwords,thework
isthesumofthetimestakenbyeachofthestrands.Foracomputationdagin
whicheachstrandtakesunittime,theworkisjustthenumberofverticesinthe
dag.Thespanisthelongesttimetoexecutethestrandsalonganypathinthedag.
Again,foradaginwhicheachstrandtakesunittime,thespanequalsthenumberof
verticesonalongestorcriticalpathinthedag.(RecallfromSection24.2thatwe
canfindacriticalpathinadagGD.VE/in.VCE/time.)Forexample,the
computationdagofFigure27.2has17verticesinalland8verticesonitscritical

Pgina201

780 Chapter27MultithreadedAlgorithms

path,sothatifeachstrandtakesunittime,itsworkis17timeunitsanditsspan
is8timeunits.
Theactualrunningtimeofamultithreadedcomputationdependsnotonlyon
itsworkanditsspan,butalsoonhowmanyprocessorsareavailableandhow
theschedulerallocatesstrandstoprocessors.Todenotetherunningtimeofa
multithreadedcomputationonPprocessors,weshallsubscriptbyP.Forexample,
wemightdenotetherunningtimeofanalgorithmonPprocessorsbyTP.El
workistherunningtimeonasingleprocessor,orT1.Thespanistherunningtime
ifwecouldruneachstrandonitsownprocessorinotherwords,ifwehadan
unlimitednumberofprocessorsandsowedenotethespanbyT1.
TheworkandspanprovidelowerboundsontherunningtimeTPofamulti
threadedcomputationonPprocessors:
Inonestep,anidealparallelcomputerwithPprocessorscandoatmostP
unitsofwork,andthusinTPtime,itcanperformatmostPTPwork.Desdeel
totalworktodoisT1,wehavePTP T1.DividingbyPyieldstheworklaw:

TP T1=P: (27.2)

APprocessoridealparallelcomputercannotrunanyfasterthanamachine
withanunlimitednumberofprocessors.Lookedatanotherway,amachine
withanunlimitednumberofprocessorscanemulateaPprocessormachineby
usingjustPofitsprocessors.Thus,thespanlawfollows:

TP T1: (27.3)

WedefinethespeedupofacomputationonPprocessorsbytheratioT1=TP,
whichsayshowmanytimesfasterthecomputationisonPprocessorsthan
on1processor.Bytheworklaw,wehaveTP T1=P,whichimpliesthat
T1=TPP.Thus,thespeeduponPprocessorscanbeatmostP.Whenthe
speedupislinearinthenumberofprocessors,thatis,whenT1=TPD.P/,the
computationexhibitslinearspeedup,andwhenT1=TPDP,wehaveperfect
linearspeedup.
TheratioT1=T1oftheworktothespangivestheparallelismofthemulti
threadedcomputation.Wecanviewtheparallelismfromthreeperspectives.Comoun
ratio,theparallelismdenotestheaverageamountofworkthatcanbeperformedin
parallelforeachstepalongthecriticalpath.Asanupperbound,theparallelism

https://translate.googleusercontent.com/translate_f 124/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
givesthemaximumpossiblespeedupthatcanbeachievedonanynumberofpro
cessors.Finally,andperhapsmostimportant,theparallelismprovidesalimiton
thepossibilityofattainingperfectlinearspeedup.Specifically,oncethenumberof
processorsexceedstheparallelism,thecomputationcannotpossiblyachieveper
fectlinearspeedup.Toseethislastpoint,supposethatP>T1=T1,inwhichcase

Pgina202

27.1Thebasicsofdynamicmultithreading 781

thespanlawimpliesthatthespeedupsatisfiesT1=TPT1=T1<P.Moreover,
ifthenumberPofprocessorsintheidealparallelcomputergreatlyexceedsthe
parallelismthatis,ifP T1=T1thenT1=TP P,sothatthespeedupis
muchlessthanthenumberofprocessors.Inotherwords,themoreprocessorswe
usebeyondtheparallelism,thelessperfectthespeedup.
Asanexample,considerthecomputationPFIB.4/inFigure27.2,andassume
thateachstrandtakesunittime.SincetheworkisT1D17andthespanisT1D8,
theparallelismisT1=T1D17=8D2:125.Consequently,achievingmuchmore
thandoublethespeedupisimpossible,nomatterhowmanyprocessorsweem
ploytoexecutethecomputation.Forlargerinputsizes,however,weshallseethat
PFIB.n/exhibitssubstantialparallelism.
Wedefinethe(parallel)slacknessofamultithreadedcomputationexecuted
onanidealparallelcomputerwithPprocessorstobetheratio.T1=T1/=PD
T1=.PT1/,whichisthefactorbywhichtheparallelismofthecomputationex
ceedsthenumberofprocessorsinthemachine.Thus,iftheslacknessislessthan1,
wecannothopetoachieveperfectlinearspeedup,becauseT1=.PT1/<1andthe
spanlawimplythatthespeeduponPprocessorssatisfiesT1=TPT1=T1<P.
Indeed,astheslacknessdecreasesfrom1toward0,thespeedupofthecomputation
divergesfurtherandfurtherfromperfectlinearspeedup.Iftheslacknessisgreater
than1,however,theworkperprocessoristhelimitingconstraint.Asweshallsee,
astheslacknessincreasesfrom1,agoodschedulercanachievecloserandcloser
toperfectlinearspeedup.

Programacin
Goodperformancedependsonmorethanjustminimizingtheworkandspan.los
strandsmustalsobescheduledefficientlyontotheprocessorsoftheparallelma
chine.Ourmultithreadedprogrammingmodelprovidesnowaytospecifywhich
strandstoexecuteonwhichprocessors.Instead,werelyontheconcurrencyplat
form'sschedulertomapthedynamicallyunfoldingcomputationtoindividualpro
cessors.Inpractice,theschedulermapsthestrandstostaticthreads,andtheop
eratingsystemschedulesthethreadsontheprocessorsthemselves,butthisextra
levelofindirectionisunnecessaryforourunderstandingofscheduling.Podemos
justimaginethattheconcurrencyplatform'sschedulermapsstrandstoprocessors
directamente.
Amultithreadedschedulermustschedulethecomputationwithnoadvance
knowledgeofwhenstrandswillbespawnedorwhentheywillcompleteitmust
operateonline.Moreover,agoodscheduleroperatesinadistributedfashion,
wherethethreadsimplementingtheschedulercooperatetoloadbalancethecom
putation.Provablygoodonline,distributedschedulersexist,butanalyzingthem
iscomplicated.

Pgina203

782 Chapter27MultithreadedAlgorithms

Instead,tokeepouranalysissimple,weshallinvestigateanonlinecentralized
scheduler,whichknowstheglobalstateofthecomputationatanygiventime.En
particular,weshallanalyzegreedyschedulers,whichassignasmanystrandsto
processorsaspossibleineachtimestep.IfatleastPstrandsarereadytoexecute
duringatimestep,wesaythatthestepisacompletestep,andagreedyscheduler
assignsanyPofthereadystrandstoprocessors.Otherwise,fewerthanPstrands
arereadytoexecute,inwhichcasewesaythatthestepisanincompletestep,and
theschedulerassignseachreadystrandtoitsownprocessor.
Fromtheworklaw,thebestrunningtimewecanhopeforonPprocessors
isTPDT1=P,andfromthespanlawthebestwecanhopeforisTPDT1.
Thefollowingtheoremshowsthatgreedyschedulingisprovablygoodinthatit
achievesthesumofthesetwolowerboundsasanupperbound.

Theorem27.1
OnanidealparallelcomputerwithPprocessors,agreedyschedulerexecutesa
multithreadedcomputationwithworkT1andspanT1intime
TPT1=PCT1: (27,4)
https://translate.googleusercontent.com/translate_f 125/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

ProofWestartbyconsideringthecompletesteps.Ineachcompletestep,the
PprocessorstogetherperformatotalofPwork.Supposeforthepurposeof
contradictionthatthenumberofcompletestepsisstrictlygreaterthanbT1=Pc.
Then,thetotalworkofthecompletestepsisatleast
P.bT1=PcC1/DPbT1=PcCP
DT1 .T1modP/CP(byequation(3.8))
>T1 (byinequality(3.9)).
Thus,weobtainthecontradictionthatthePprocessorswouldperformmorework
thanthecomputationrequires,whichallowsustoconcludethatthenumberof
completestepsisatmostbT1=Pc.
Now,consideranincompletestep.LetGbethedagrepresentingtheentire
computation,andwithoutlossofgenerality,assumethateachstrandtakesunit
hora.(Wecanreplaceeachlongerstrandbyachainofunittimestrands.)LetG0
bethesubgraphofGthathasyettobeexecutedatthestartoftheincompletestep,
andletG00bethesubgraphremainingtobeexecutedaftertheincompletestep.UN
longestpathinadagmustnecessarilystartatavertexwithindegree0.Sincean
incompletestepofagreedyschedulerexecutesallstrandswithindegree0inG0,
thelengthofalongestpathinG00mustbe1lessthanthelengthofalongestpath
inG0.Inotherwords,anincompletestepdecreasesthespanoftheunexecuteddag
by1.Hence,thenumberofincompletestepsisatmostT1.
Sinceeachstepiseithercompleteorincomplete,thetheoremfollows.

Pgina204

27.1Thebasicsofdynamicmultithreading 783

ThefollowingcorollarytoTheorem27.1showsthatagreedyscheduleralways
performswell.

Corollary27.2
TherunningtimeTPofanymultithreadedcomputationscheduledbyagreedy
scheduleronanidealparallelcomputerwithPprocessorsiswithinafactorof2
ofoptimal.

ProofLetTPbetherunningtimeproducedbyanoptimalscheduleronamachine
withPprocessors,andletT1andT1betheworkandspanofthecomputation,
respectivamente.Sincetheworkandspanlawsinequalities(27.2)and(27.3)give
usTP max.T1=PT1/,Theorem27.1impliesthat
TP T1=PCT1
2max.T1=PT1/
2TP:

Thenextcorollaryshowsthat,infact,agreedyschedulerachievesnearperfect
linearspeeduponanymultithreadedcomputationastheslacknessgrows.

Corollary27.3
LetTPbetherunningtimeofamultithreadedcomputationproducedbyagreedy
scheduleronanidealparallelcomputerwithPprocessors,andletT1andT1be
theworkandspanofthecomputation,respectively.Then,ifP T1=T1,we
haveTP T1=P,orequivalently,aspeedupofapproximatelyP.

ProofIfwesupposethatP T1=T1,thenwealsohaveT1 T1=P,and


henceTheorem27.1givesusTP T1=PCT1 T1=P.Sincethework
law(27.2)dictatesthatTP T1=P,weconcludethatTP T1=P,orequiva
lently,thatthespeedupisT1=TP PAG.

los symboldenotesmuchless,buthowmuchismuchless?Asarule
ofthumb,aslacknessofatleast10thatis,10timesmoreparallelismthanpro
cessorsgenerallysufficestoachievegoodspeedup.Then,thespanterminthe
greedybound,inequality(27.4),islessthan10%oftheworkperprocessorterm,
whichisgoodenoughformostengineeringsituations.Forexample,ifacomputa
tionrunsononly10or100processors,itdoesn'tmakesensetovalueparallelism
of,say1,000,000overparallelismof10,000,evenwiththefactorof100differ
LaAsProblem272shows,sometimesbyreducingextremeparallelism,we
canobtainalgorithmsthatarebetterwithrespecttootherconcernsandwhichstill
scaleupwellonreasonablenumbersofprocessors.

Pgina205

https://translate.googleusercontent.com/translate_f 126/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
784 Chapter27MultithreadedAlgorithms

UN
UN segundo
segundo

Work:T .A[B/DT .A/CT .B/


1 1 1 Work:T .A[B/DT .A/CT .B/
1 1 1

Span:T .A[B/DT .A/CT .B/


1 1 1 Span:T .A[B/Dmax.T .A/T .B/)
1 1 1

(un) (segundo)

Figure27.3Theworkandspanofcomposedsubcomputations.(a)Whentwosubcomputations
arejoinedinseries,theworkofthecompositionisthesumoftheirwork,andthespanofthe
compositionisthesumoftheirspans.(b)Whentwosubcomputationsarejoinedinparallel,the
workofthecompositionremainsthesumoftheirwork,butthespanofthecompositionisonlythe
maximumoftheirspans.

Analyzingmultithreadedalgorithms
Wenowhaveallthetoolsweneedtoanalyzemultithreadedalgorithmsandprovide
goodboundsontheirrunningtimesonvariousnumbersofprocessors.Analizando
theworkisrelativelystraightforward,sinceitamountstonothingmorethanana
lyzingtherunningtimeofanordinaryserialalgorithmnamely,theserialization
ofthemultithreadedalgorithmwhichyoushouldalreadybefamiliarwith,since
thatiswhatmostofthistextbookisabout!Analyzingthespanismoreinteresting,
butgenerallynoharderonceyougetthehangofit.Weshallinvestigatethebasic
ideasusingthePFIBprogram.
AnalyzingtheworkT1.n/ofPFIB.n/posesnohurdles,becausewe'vealready
doneit.TheoriginalFIBprocedureisessentiallytheserializationofPFIB,and
henceT1.n/DT.n/D.n/fromequation(27.1).
Figure27.3illustrateshowtoanalyzethespan.Iftwosubcomputationsare
joinedinseries,theirspansaddtoformthespanoftheircomposition,whereas
iftheyarejoinedinparallel,thespanoftheircompositionisthemaximumofthe
spansofthetwosubcomputations.ForPFIB.n/,thespawnedcalltoPFIB.n1/
inline3runsinparallelwiththecalltoPFIB.n2/inline4.Hence,wecan
expressthespanofPFIB.n/astherecurrence
T1.n/Dmax.T1.n1/T1.n2//C.1/
DT1.n1/C.1/
whichhassolutionT1.n/D.n/.
TheparallelismofPFIB.n/isT1.n/=T1.n/D.n=n/,whichgrowsdra
maticallyasngetslarge.Thus,oneventhelargestparallelcomputers,amodest

Pgina206

27.1Thebasicsofdynamicmultithreading 785

valuefornsufficestoachievenearperfectlinearspeedupforPFIB.n/,because
thisprocedureexhibitsconsiderableparallelslackness.

Parallelloops

Manyalgorithmscontainloopsallofwhoseiterationscanoperateinparallel.Como
weshallsee,wecanparallelizesuchloopsusingthespawnandsynckeywords,
butitismuchmoreconvenienttospecifydirectlythattheiterationsofsuchloops
canrunconcurrently.Ourpseudocodeprovidesthisfunctionalityviatheparallel
concurrencykeyword,whichprecedestheforkeywordinaforloopstatement.
Asanexample,considertheproblemofmultiplyingannnmatrixAD.aij/
byannvectorxD.xj/.TheresultingnvectoryD.yi/isgivenbytheequation
xnorte
yiD aijxj
jD1
foriD12:::norte.Wecanperformmatrixvectormultiplicationbycomputingall
theentriesofyinparallelasfollows:

MATVEC.Ax/
1nDA:rows
2letybeanewvectoroflengthn
3parallelforiD1ton
4 yiD0
5parallelforiD1ton
6 forjD1ton
7 yiDyiCaijxj
8returny

https://translate.googleusercontent.com/translate_f 127/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Inthiscode,theparallelforkeywordsinlines3and5indicatethattheitera
tionsoftherespectiveloopsmayberunconcurrently.Acompilercanimplement
eachparallelforloopasadivideandconquersubroutineusingnestedparallelism.
Forexample,theparallelforloopinlines57canbeimplementedwiththecall
MATVECMAINLOOP.AxYn1n/,wherethecompilerproducestheauxil
iarysubroutineMATVECMAINLOOPasfollows:

Pgina207

786 Chapter27MultithreadedAlgorithms

1,8

1,4 5,8

1,2 3,4 5,6 7,8

1,1 2,2 3,3 4,4 5,5 6,6 7,7 8,8

Figure27.4AdagrepresentingthecomputationofMATVECMAINLOOP.AxY818/.El
twonumberswithineachroundedrectanglegivethevaluesofthelasttwoparameters(iandi0in
theprocedureheader)intheinvocation(spawnorcall)oftheprocedure.Theblackcirclesrepre
sentstrandscorrespondingtoeitherthebasecaseorthepartoftheprocedureuptothespawnof
MATVECMAINLOOPinline5theshadedcirclesrepresentstrandscorrespondingtothepartof
theprocedurethatcallsMATVECMAINLOOPinline6uptothesyncinline7,whereitsuspends
untilthespawnedsubroutineinline5returnsandthewhitecirclesrepresentstrandscorresponding
tothe(negligible)partoftheprocedureafterthesyncuptothepointwhereitreturns.

MATVECMAINLOOP.AxYnii0/
1ifi==i0
2 forjD1ton
3 yiDyiCaijxj
4elsemidDbiCi0/=2c
5 spawnMATVECMAINLOOP.AxYnimid/
6 MATVECMAINLOOP.AxYnmidC1i0/
7 sync

Thiscoderecursivelyspawnsthefirsthalfoftheiterationsofthelooptoexecute
inparallelwiththesecondhalfoftheiterationsandthenexecutesasync,thereby
creatingabinarytreeofexecutionwheretheleavesareindividualloopiterations,
asshowninFigure27.4.
TocalculatetheworkT1.n/ofMATVEConannnmatrix,wesimplycompute
therunningtimeofitsserialization,whichweobtainbyreplacingtheparallelfor
loopswithordinaryforloops.Thus,wehaveT1.n/D.n2/,becausethequa
draticrunningtimeofthedoublynestedloopsinlines57dominates.Esteanlisis

Pgina208

27.1Thebasicsofdynamicmultithreading 787

seemstoignoretheoverheadforrecursivespawninginimplementingtheparallel
loops,however.Infact,theoverheadofrecursivespawningdoesincreasethework
ofaparallelloopcomparedwiththatofitsserialization,butnotasymptotically.
Toseewhy,observethatsincethetreeofrecursiveprocedureinstancesisafull
binarytree,thenumberofinternalnodesis1fewerthanthenumberofleaves(see
ExerciseB.53).Eachinternalnodeperformsconstantworktodividetheiteration
range,andeachleafcorrespondstoaniterationoftheloop,whichtakesatleast
constanttime(.n/timeinthiscase).Thus,wecanamortizetheoverheadofre
cursivespawningagainsttheworkoftheiterations,contributingatmostaconstant

https://translate.googleusercontent.com/translate_f 128/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
factortotheoverallwork.
Asapracticalmatter,dynamicmultithreadingconcurrencyplatformssometimes
coarsentheleavesoftherecursionbyexecutingseveraliterationsinasingleleaf,
eitherautomaticallyorunderprogrammercontrol,therebyreducingtheoverhead
ofrecursivespawning.Thisreducedoverheadcomesattheexpenseofalsoreduc
ingtheparallelism,however,butifthecomputationhassufficientparallelslack
ness,nearperfectlinearspeedupneednotbesacrificed.
Wemustalsoaccountfortheoverheadofrecursivespawningwhenanalyzingthe
spanofaparallelloopconstruct.Sincethedepthofrecursivecallingislogarithmic
inthenumberofiterations,foraparallelloopwithniterationsinwhichtheith
iterationhasspaniter1.i/,thespanis
T1.n/D.lgn/Cmax iter1.i/:
1in
Forexample,forMATVEConannnmatrix,theparallelinitializationloopin
lines34hasspan.lgn/,becausetherecursivespawningdominatestheconstant
timeworkofeachiteration.Thespanofthedoublynestedloopsinlines57
is.n/,becauseeachiterationoftheouterparallelforloopcontainsniterations
oftheinner(serial)forloop.Thespanoftheremainingcodeintheprocedure
isconstant,andthusthespanisdominatedbythedoublynestedloops,yielding
anoverallspanof.n/forthewholeprocedure.Sincetheworkis.n2/,the
parallelismis.n2/=.n/D.n/.(Exercise27.16asksyoutoprovidean
implementationwithevenmoreparallelism.)

Raceconditions
Amultithreadedalgorithmisdeterministicifitalwaysdoesthesamethingonthe
sameinput,nomatterhowtheinstructionsarescheduledonthemulticorecom
puter.Itisnondeterministicifitsbehaviormightvaryfromruntorun.Often,a
multithreadedalgorithmthatisintendedtobedeterministicfailstobe,becauseit
containsadeterminacyrace.
Raceconditionsarethebaneofconcurrency.Famousracebugsincludethe
Therac25radiationtherapymachine,whichkilledthreepeopleandinjuredsev

Pgina209

788 Chapter27MultithreadedAlgorithms

eralothers,andtheNorthAmericanBlackoutof2003,whichleftover50million
peoplewithoutpower.Theseperniciousbugsarenotoriouslyhardtofind.Ustedpuede
runtestsinthelabfordayswithoutafailureonlytodiscoverthatyoursoftware
sporadicallycrashesinthefield.
Adeterminacyraceoccurswhentwologicallyparallelinstructionsaccessthe
samememorylocationandatleastoneoftheinstructionsperformsawrite.los
followingprocedureillustratesaracecondition:

RACEEXAMPLE./
1xD0
2parallelforiD1to2
3 xDxC1
4printx

Afterinitializingxto0inline1,RACEEXAMPLEcreatestwoparallelstrands,
eachofwhichincrementsxinline3.AlthoughitmightseemthatRACE
EXAMPLEshouldalwaysprintthevalue2(itsserializationcertainlydoes),itcould
insteadprintthevalue1.Let'sseehowthisanomalymightoccur.
Whenaprocessorincrementsx,theoperationisnotindivisible,butiscomposed
ofasequenceofinstructions:
1.Readxfrommemoryintooneoftheprocessor'sregisters.
2.Incrementthevalueintheregister.
3.Writethevalueintheregisterbackintoxinmemory.
Figure27.5(a)illustratesacomputationdagrepresentingtheexecutionofRACE
EXAMPLE,withthestrandsbrokendowntoindividualinstructions.Recallthat
sinceanidealparallelcomputersupportssequentialconsistency,wecanviewthe
parallelexecutionofamultithreadedalgorithmasaninterleavingofinstructions
thatrespectsthedependenciesinthedag.Part(b)ofthefigureshowsthevalues
inanexecutionofthecomputationthatelicitstheanomaly.Thevaluexisstored
inmemory,andr1andr2areprocessorregisters.Instep1,oneoftheprocessors
setsxto0.Insteps2and3,processor1readsxfrommemoryintoitsregisterr1
andincrementsit,producingthevalue1inr1.Atthatpoint,processor2comes
intothepicture,executinginstructions46.Processor2readsxfrommemoryinto
registerr2incrementsit,producingthevalue1inr2andthenstoresthisvalue
intox,settingxto1.Now,processor1resumeswithstep7,storingthevalue1
inr1intox,whichleavesthevalueofxunchanged.Therefore,step8printsthe
value1,ratherthan2,astheserializationwouldprint.
Wecanseewhathashappened.Iftheeffectoftheparallelexecutionwerethat
https://translate.googleusercontent.com/translate_f 129/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
processor1executedallitsinstructionsbeforeprocessor2,thevalue2wouldbe

Pgina210

27.1Thebasicsofdynamicmultithreading 789

1 x=0
step x r1 r2
2 r1 =x 4 r2 =x 1 0
2 0 0
3 incrr1 5 incrr2 3 0 1
4 0 1 0
7 x=r1 6 x=r2 5 0 1 1
6 1 1 1
8 printx 7 1 1 1

(un) (segundo)

Figure27.5IllustrationofthedeterminacyraceinRACEEXAMPLE.(a)Acomputationdagshow
ingthedependenciesamongindividualinstructions.Theprocessorregistersarer1andr2.Instruc
tionsunrelatedtotherace,suchastheimplementationofloopcontrol,areomitted.(b)Anexecution
sequencethatelicitsthebug,showingthevaluesofxinmemoryandregistersr1andr2foreach
stepintheexecutionsequence.

impreso.Conversely,iftheeffectwerethatprocessor2executedallitsinstructions
beforeprocessor1,thevalue2wouldstillbeprinted.Whentheinstructionsofthe
twoprocessorsexecuteatthesametime,however,itispossible,asinthisexample
execution,thatoneoftheupdatestoxislost.
Ofcourse,manyexecutionsdonotelicitthebug.Forexample,iftheexecution
orderwereh12374568iorh14562378i,wewouldgetthecor
rectresult.That'stheproblemwithdeterminacyraces.Generally,mostorderings
producecorrectresultssuchasanyinwhichtheinstructionsontheleftexecute
beforetheinstructionsontheright,orviceversa.Butsomeorderingsgenerate
improperresultswhentheinstructionsinterleave.Consequently,racescanbeex
tremelyhardtotestfor.Youcanruntestsfordaysandneverseethebug,onlyto
experienceacatastrophicsystemcrashinthefieldwhentheoutcomeiscritical.
Althoughwecancopewithracesinavarietyofways,includingusingmutual
exclusionlocksandothermethodsofsynchronization,forourpurposes,weshall
simplyensurethatstrandsthatoperateinparallelareindependent:theyhaveno
determinacyracesamongthem.Thus,inaparallelforconstruct,alltheiterations
shouldbeindependent.Betweenaspawnandthecorrespondingsync,thecode
ofthespawnedchildshouldbeindependentofthecodeoftheparent,including
codeexecutedbyadditionalspawnedorcalledchildren.Notethatargumentstoa
spawnedchildareevaluatedintheparentbeforetheactualspawnoccurs,andthus
theevaluationofargumentstoaspawnedsubroutineisinserieswithanyaccesses
tothoseargumentsafterthespawn.

Page211

790 Chapter27MultithreadedAlgorithms

Asanexampleofhoweasyitistogeneratecodewithraces,hereisafaulty
implementationofmultithreadedmatrixvectormultiplicationthatachievesaspan
of.lgn/byparallelizingtheinnerforloop:
MATVECWRONG.Ax/
1nDA:rows
2letybeanewvectoroflengthn
3parallelforiD1ton
4 yiD0
5parallelforiD1ton
6 parallelforjD1ton
7 yiDyiCaijxj
8returny
Thisprocedureis,unfortunately,incorrectduetoracesonupdatingyiinline7,
whichexecutesconcurrentlyforallnvaluesofj.Exercise27.16asksyoutogive
acorrectimplementationwith.lgn/span.
Amultithreadedalgorithmwithracescansometimesbecorrect.Asanexam
ple,twoparallelthreadsmightstorethesamevalueintoasharedvariable,andit
wouldn'tmatterwhichstoredthevaluefirst.Generally,however,weshallconsider
codewithracestobeillegal.

https://translate.googleusercontent.com/translate_f 130/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Achesslesson
Weclosethissectionwithatruestorythatoccurredduringthedevelopmentof
theworldclassmultithreadedchessplayingprogram?Socrates[80],althoughthe
timingsbelowhavebeensimplifiedforexposition.Theprogramwasprototyped
ona32processorcomputerbutwasultimatelytorunonasupercomputerwith512
ProcesadoresAtonepoint,thedevelopersincorporatedanoptimizationintothepro
gramthatreduceditsrunningtimeonanimportantbenchmarkonthe32processor
machinefromT32D65secondstoT0 32D40seconds.Yet,thedevelopersused
theworkandspanperformancemeasurestoconcludethattheoptimizedversion,
whichwasfasteron32processors,wouldactuallybeslowerthantheoriginalver
sionon512processsors.Asaresult,theyabandonedtheoptimization.
Hereistheiranalysis.TheoriginalversionoftheprogramhadworkT1D2048
secondsandspanT1D1second.Ifwetreatinequality(27.4)asanequation,
TPDT1=PCT1,anduseitasanapproximationtotherunningtimeonPpro
cessors,weseethatindeedT32D2048=32C1D65.Withtheoptimization,the
workbecameT0
1D1024secondsandthespanbecameT0 1D8seconds. Denuevo
usingourapproximation,wegetT032D1024=32C8D40.
Therelativespeedsofthetwoversionsswitchwhenwecalculatetherunning
timeson512processors,however.Inparticular,wehaveT512D2048=512C1D5

Pgina212

27.1Thebasicsofdynamicmultithreading 791

seconds,andT512
0
D1024=512C8D10seconds.Theoptimizationthatspedup
theprogramon32processorswouldhavemadetheprogramtwiceasslowon512
processors!Theoptimizedversion'sspanof8,whichwasnotthedominanttermin
therunningtimeon32processors,becamethedominanttermon512processors,
nullifyingtheadvantagefromusingmoreprocessors.
Themoralofthestoryisthatworkandspancanprovideabettermeansof
extrapolatingperformancethancanmeasuredrunningtimes.

Exercises

27.11
SupposethatwespawnPFIB.n 2/inline4ofPFIB,ratherthancallingit
asisdoneinthecode.Whatistheimpactontheasymptoticwork,span,and
parallelism?

27.12
DrawthecomputationdagthatresultsfromexecutingPFIB.5/.Assumingthat
eachstrandinthecomputationtakesunittime,whatarethework,span,andpar
allelismofthecomputation?Showhowtoschedulethedagon3processorsusing
greedyschedulingbylabelingeachstrandwiththetimestepinwhichitisexecuted.

27.13
Provethatagreedyschedulerachievesthefollowingtimebound,whichisslightly
strongerthantheboundproveninTheorem27.1:
T1 T1
TP CT1: (27.5)
PAG

27.14
Constructacomputationdagforwhichoneexecutionofagreedyschedulercan
takenearlytwicethetimeofanotherexecutionofagreedyscheduleronthesame
numberofprocessors.Describehowthetwoexecutionswouldproceed.

27.15
ProfessorKaranmeasuresherdeterministicmultithreadedalgorithmon4,10,
and64processorsofanidealparallelcomputerusingagreedyscheduler.Ella
claimsthatthethreerunsyieldedT4D80seconds,T10D42seconds,and
T64D10seconds.Arguethattheprofessoriseitherlyingorincompetent.(Hint:
Usetheworklaw(27.2),thespanlaw(27.3),andinequality(27.5)fromExer
cise27.13.)

Pgina213

792 Chapter27MultithreadedAlgorithms

27.16

https://translate.googleusercontent.com/translate_f 131/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Giveamultithreadedalgorithmtomultiplyannnmatrixbyannvectorthat
achieves.n2=lgn/parallelismwhilemaintaining.n2/work.

27.17
ConsiderthefollowingmultithreadedpseudocodefortransposingannnmatrixA
inplace:

PTRANSPOSE.A/
1nDA:rows
2parallelforjD2ton
3 parallelforiD1toj 1
4 exchangeaijwithaji

Analyzethework,span,andparallelismofthisalgorithm.

27.18
Supposethatwereplacetheparallelforloopinline3ofPTRANSPOSE(seeEx
ercise27.17)withanordinaryforloop.Analyzethework,span,andparallelism
oftheresultingalgorithm.

27.19
Forhowmanyprocessorsdothetwoversionsofthechessprogramsrunequally
fast,assumingthatTPDT1=PCT1?

27.2Multithreadedmatrixmultiplication

Inthissection,weexaminehowtomultithreadmatrixmultiplication,aproblem
whoseserialrunningtimewestudiedinSection4.2.We'lllookatmultithreaded
algorithmsbasedonthestandardtriplynestedloop,aswellasdivideandconquer
Algoritmos

Multithreadedmatrixmultiplication
Thefirstalgorithmwestudyisthestraighforwardalgorithmbasedonparallelizing
theloopsintheprocedureSQUAREMATRIXMULTIPLYonpage75:

Pgina214

27.2Multithreadedmatrixmultiplication 793

PSQUAREMATRIXMULTIPLY.AB/
1nDA:rows
2letCbeanewnnmatrix
3parallelforiD1ton
4 parallelforjD1ton
5 cijD0
6 forkD1ton
7 cijDcijCaik bkj
8returnC

Toanalyzethisalgorithm,observethatsincetheserializationofthealgorithmis
justSQUAREMATRIXMULTIPLY,theworkisthereforesimplyT1.n/D.n3/,
thesameastherunningtimeofSQUAREMATRIXMULTIPLY.Thespanis
T1.n/D.n/,becauseitfollowsapathdownthetreeofrecursionforthe
parallelforloopstartinginline3,thendownthetreeofrecursionfortheparallel
forloopstartinginline4,andthenexecutesallniterationsoftheordinaryforloop
startinginline6,resultinginatotalspanof.lgn/C.lgn/C.n/D.n/.
Thus,theparallelismis.n3/=.n/D.n2/.Exercise27.23asksyoutopar
allelizetheinnerlooptoobtainaparallelismof.n3=lgn/,whichyoucannotdo
straightforwardlyusingparallelfor,becauseyouwouldcreateraces.

Adivideandconquermultithreadedalgorithmformatrixmultiplication
AswelearnedinSection4.2,wecanmultiplyn nmatricesseriallyintime
.nlg7/DOn2:81/usingStrassen'sdivideandconquerstrategy,whichmotivates
ustolookatmultithreadingsuchanalgorithm.Webegin,aswedidinSection4.2,
withmultithreadingasimplerdivideandconqueralgorithm.
Recallfrompage77thattheSQUAREMATRIXMULTIPLYRECURSIVEproce
dure,whichmultipliestwonnmatricesAandBtoproducethennmatrixC,
reliesonpartitioningeachofthethreematricesintofourn=2n=2submatrices:
UN UN UN UN UN UN
A11 A12 B11 B12 C11 C12
ANUNCIO BD discoscompactos :

https://translate.googleusercontent.com/translate_f 132/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
A21 A22 B21 B22 C21 C22
Then,wecanwritethematrixproductas
UN UN UN UN
C11 C12 A11 A12 B11 B12
re
C21 C22 A21 A22 B21 B22
UN UN UN UN
A11B11 A11B12 A12B21 A12B22
re do : (27.6)
A21B11 A21B12 A22B21 A22B22
Thus,tomultiplytwonnmatrices,weperformeightmultiplicationsofn=2n=2
matricesandoneadditionofnnmatrices.Thefollowingpseudocodeimplements

Pgina215

794 Chapter27MultithreadedAlgorithms

thisdivideandconquerstrategyusingnestedparallelism.UnliketheSQUARE
MATRIXMULTIPLYRECURSIVEprocedureonwhichitisbased,PMATRIX
MULTIPLYRECURSIVEtakestheoutputmatrixasaparametertoavoidallocating
matricesunnecessarily.

PMATRIXMULTIPLYRECURSIVE.CAB/
1nDA:rows
2ifn==1
3 c11Da11b11
4elseletTbeanewnnmatrix
5 partitionA,B,C,andTinton=2n=2submatrices
A11A12A21A22B11B12B21B22C11C12C21C22
andT11T12T21T22respectivamente
6 spawnPMATRIXMULTIPLYRECURSIVE.C11A11B11/
7 spawnPMATRIXMULTIPLYRECURSIVE.C12A11B12/
8 spawnPMATRIXMULTIPLYRECURSIVE.C21A21B11/
9 spawnPMATRIXMULTIPLYRECURSIVE.C22A21B12/
10 spawnPMATRIXMULTIPLYRECURSIVE.T11A12B21/
11 spawnPMATRIXMULTIPLYRECURSIVE.T12A12B22/
12 spawnPMATRIXMULTIPLYRECURSIVE.T21A22B21/
13 PMATRIXMULTIPLYRECURSIVE.T22A22B22/
14 sync
15 parallelforiD1ton
diecisis parallelforjD1ton
17 cijDcijCtij

Line3handlesthebasecase,wherewearemultiplying11matrices.Wehandle
therecursivecaseinlines417.WeallocateatemporarymatrixTinline4,and
line5partitionseachofthematricesA,B,C,andTinton=2n=2submatrices.
(AswithSQUAREMATRIXMULTIPLYRECURSIVEonpage77,weglossover
theminorissueofhowtouseindexcalculationstorepresentsubmatrixsections
ofamatrix.)Therecursivecallinline6setsthesubmatrixC11tothesubmatrix
productA11B11,sothatC11equalsthefirstofthetwotermsthatformitssumin
equation(27.6).Similarly,lines79setC12,C21,andC22tothefirstofthetwo
termsthatequaltheirsumsinequation(27.6).Line10setsthesubmatrixT11to
thesubmatrixproductA12B21,sothatT11equalsthesecondofthetwotermsthat
formC11ssum.Lines1113setT12,T21,andT22tothesecondofthetwoterms
thatformthesumsofC12,C21,andC22,respectively.Thefirstsevenrecursive
callsarespawned,andthelastonerunsinthemainstrand.Thesyncstatementin
line14ensuresthatallthesubmatrixproductsinlines613havebeencomputed,

Pgina216

27.2Multithreadedmatrixmultiplication 795

afterwhichweaddtheproductsfromTintoCinusingthedoublynestedparallel
forloopsinlines1517.
WefirstanalyzetheworkM1.n/ofthePMATRIXMULTIPLYRECURSIVE
procedure,echoingtheserialrunningtimeanalysisofitsprogenitorSQUARE
MATRIXMULTIPLYRECURSIVE.Intherecursivecase,wepartitionin.1/time,
performeightrecursivemultiplicationsofn=2n=2matrices,andfinishupwith
the.n2/workfromaddingtwon nmatrices.Thus,therecurrenceforthe
workM1.n/is
M1.n/D8M1.n=2/C.n2/
D.n3/
bycase1ofthemastertheorem.Inotherwords,theworkofourmultithreadedal

https://translate.googleusercontent.com/translate_f 133/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
gorithmisasymptoticallythesameastherunningtimeoftheprocedureSQUARE
MATRIXMULTIPLYinSection4.2,withitstriplynestedloops.
TodeterminethespanM1.n/ofPMATRIXMULTIPLYRECURSIVE,wefirst
observethatthespanforpartitioningis.1/,whichisdominatedbythe.lgn/
spanofthedoublynestedparallelforloopsinlines1517.Becausetheeight
parallelrecursivecallsallexecuteonmatricesofthesamesize,themaximumspan
foranyrecursivecallisjustthespanofanyone.Hence,therecurrenceforthe
spanM1.n/ofPMATRIXMULTIPLYRECURSIVEis
M1.n/DM1.n=2/C.lgn/: (27.7)
Thisrecurrencedoesnotfallunderanyofthecasesofthemastertheorem,but
itdoesmeettheconditionofExercise4.62.ByExercise4.62,therefore,the
solutiontorecurrence(27.7)isM1.n/D.lg2n/.
NowthatweknowtheworkandspanofPMATRIXMULTIPLYRECURSIVE,
wecancomputeitsparallelismasM1.n/=M1.n/D.n3=lg2n/,whichisvery
alto.

MultithreadingStrassen'smethod
TomultithreadStrassen'salgorithm,wefollowthesamegeneraloutlineason
page79,onlyusingnestedparallelism:
1.DividetheinputmatricesAandBandoutputmatrixCinton=2n=2sub
matrices,asinequation(27.6).Thissteptakes.1/workandspanbyindex
clculo.
2.Create10matricesS1S2:::S10,eachofwhichisn=2n=2andisthesum
ordifferenceoftwomatricescreatedinstep1.Wecancreateall10matrices
with.n2/workand.lgn/spanbyusingdoublynestedparallelforloops.

Pgina217

796 Chapter27MultithreadedAlgorithms

3.Usingthesubmatricescreatedinstep1andthe10matricescreatedin
step2,recursivelyspawnthecomputationofsevenn=2n=2matrixproducts
P1P2:::P7.
4.ComputethedesiredsubmatricesC11C12C21C22oftheresultmatrixCby
addingandsubtractingvariouscombinationsofthePimatrices,onceagain
usingdoublynestedparallelforloops.Wecancomputeallfoursubmatrices
with.n2/workand.lgn/span.
Toanalyzethisalgorithm,wefirstobservethatsincetheserializationisthe
sameastheoriginalserialalgorithm,theworkisjusttherunningtimeofthe
serialization,namely,.nlg7/.AsforPMATRIXMULTIPLYRECURSIVE,we
candevisearecurrenceforthespan.Inthiscase,sevenrecursivecallsexe
cuteinparallel,butsincetheyalloperateonmatricesofthesamesize,weob
tainthesamerecurrence(27.7)aswedidforPMATRIXMULTIPLYRECURSIVE,
whichhassolution.lg2n/.Thus,theparallelismofmultithreadedStrassens
methodis.nlg7=lg2n/,whichishigh,thoughslightlylessthantheparallelism
ofPMATRIXMULTIPLYRECURSIVE.

Exercises

27.21
DrawthecomputationdagforcomputingPSQUAREMATRIXMULTIPLYon22
matrices,labelinghowtheverticesinyourdiagramcorrespondtostrandsinthe
executionofthealgorithm.Usetheconventionthatspawnandcalledgespoint
downward,continuationedgespointhorizontallytotheright,andreturnedges
pointupward.Assumingthateachstrandtakesunittime,analyzethework,span,
andparallelismofthiscomputation.

27.22
RepeatExercise27.21forPMATRIXMULTIPLYRECURSIVE.

27.23
Givepseudocodeforamultithreadedalgorithmthatmultipliestwonnmatrices
withwork.n3/butspanonly.lgn/.Analyzeyouralgorithm.

27.24
Givepseudocodeforanefficientmultithreadedalgorithmthatmultipliesapq
matrixbyaqrmatrix.Youralgorithmshouldbehighlyparallelevenifanyof
p,q,andrare1.Analyzeyouralgorithm.

https://translate.googleusercontent.com/translate_f 134/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina218

27.3Multithreadedmergesort 797

27.25
Givepseudocodeforanefficientmultithreadedalgorithmthattransposesannn
matrixinplacebyusingdivideandconquertodividethematrixrecursivelyinto
fourn=2n=2submatrices.Analyzeyouralgorithm.

27.26
GivepseudocodeforanefficientmultithreadedimplementationoftheFloyd
Warshallalgorithm(seeSection25.2),whichcomputesshortestpathsbetweenall
pairsofverticesinanedgeweightedgraph.Analyzeyouralgorithm.

27.3Multithreadedmergesort

WefirstsawserialmergesortinSection2.3.1,andinSection2.3.2weanalyzedits
runningtimeandshowedittobe.nlgn/.Becausemergesortalreadyusesthe
divideandconquerparadigm,itseemslikeaterrificcandidateformultithreading
usingnestedparallelism.Wecaneasilymodifythepseudocodesothatthefirst
recursivecallisspawned:

MERGESORT 0.Apr/
1ifp<r
2 qDbpCr/=2c
3 spawnMERGESORT 0.ApQ
4 MERGESORT 0.AqC1r/
5 sync
6 MERGE.Apqr/

Likeitsserialcounterpart,MERGESORT 0sortsthesubarrayAp::r.Afterthe
tworecursivesubroutinesinlines3and4havecompleted,whichisensuredbythe
syncstatementinline5,MERGESORT 0callsthesameMERGEprocedureason
page31.
LetusanalyzeMERGESORT 0. Todoso,wefirstneedtoanalyzeMERGE. Re
callthatitsserialrunningtimetomergenelementsis.n/.BecauseMERGEis
serial,bothitsworkanditsspanare.n/.Thus,thefollowingrecurrencecharac
terizestheworkMS1 0onnelements:
0
.n/ofMERGESORT
MS10
.n/D2MS0 1.n=2/C.n/
D.nlgn/

Page219

798 Chapter27MultithreadedAlgorithms

p 1 q1 r1 p2 q r2 2

T ... x x x ... <x x ...

merge dupdo merge


UN ... x x x ...
p3 q
3 r3

Figure27.6TheideabehindthemultithreadedmergingoftwosortedsubarraysTp1::r1
andTp2::r2intothesubarrayAp3::r3.LettingxDTq1bethemedianofTp1::r1andq2
1andTq
betheplaceinTp2::r2suchthatxwouldfallbetweenTq 2 2,everyelementin

subarraysTp1::q1andTp
1 2::q21(lightlyshaded)islessthanorequaltox,andevery

elementinthesubarraysTq1C1::r1andTq2C1::r2(heavilyshaded)isatleastx.Tomerge,
wecomputetheindexq3wherexbelongsinAp3::r3,copyxintoAq3,andthenrecursively
mergeTp1::q1withTp
1 2::q1
2 intoAp3::q31andTq1C1::r1withTq2::r2

intoAq3C1::r3.

whichisthesameastheserialrunningtimeofmergesort.Sincethetworecursive
callsofMERGESORT 0canruninparallel,thespanMS0 1isgivenbytherecurrence
MS1
0
.n/DMS0 1.n=2/C.n/
D.n/:
Thus,theparallelismofMERGESORT 0comestoMS0
https://translate.googleusercontent.com/translate_f 135/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
1.n/=MS0
1.n/D.lgn/,
whichisanunimpressiveamountofparallelism.Tosort10millionelements,for
example,itmightachievelinearspeeduponafewprocessors,butitwouldnot
scaleupeffectivelytohundredsofprocessors.
Youprobablyhavealreadyfiguredoutwheretheparallelismbottleneckisin
thismultithreadedmergesort:theserialMERGEprocedure.Althoughmerging
mightinitiallyseemtobeinherentlyserial,wecan,infact,fashionamultithreaded
versionofitbyusingnestedparallelism.
Ourdivideandconquerstrategyformultithreadedmerging,whichisillus
tratedinFigure27.6,operatesonsubarraysofanarrayT.Supposethatwe
aremergingthetwosortedsubarraysTp1::r1oflengthn1Dr1 p1C1
andTp2::r2oflengthn2Dr2 p2C1intoanothersubarrayAp3::r3,of
lengthn3Dr3 p3C1Dn1Cn2.Withoutlossofgenerality,wemakethesim
plifyingassumptionthatn1 n2.
WefirstfindthemiddleelementxDTq1ofthesubarrayTp1::r1,
whereq1Dbp1Cr1/=2c.Becausethesubarrayissorted,xisamedian
ofTp1::r1:everyelementinTp1::q1 1isnomorethanx,andeveryel
ementinTq1C1::r1isnolessthanx.Wethenusebinarysearchtofindthe

Pgina220

27.3Multithreadedmergesort 799

indexq2inthesubarrayTp2::r2sothatthesubarraywouldstillbesortedifwe
insertedxbetweenTq2 1andTq2.
WenextmergetheoriginalsubarraysTp1::r1andTp2::r2intoAp3::r3
comosigue:
1.Setq3Dp3C.q1 p1/C.q2 p2/.
2.CopyxintoAq3.
3.RecursivelymergeTp1::q1 1withTp2::q2 1,andplacetheresultinto
thesubarrayAp3::q3 1.
4.RecursivelymergeTq1C1::r1withTq2::r2,andplacetheresultintothe
subarrayAq3C1::r3.
Whenwecomputeq3,thequantityq1 p1isthenumberofelementsinthesubarray
Tp1::q1 1,andthequantityq2 p2isthenumberofelementsinthesubarray
Tp2::q2 1.Thus,theirsumisthenumberofelementsthatendupbeforexin
thesubarrayAp3::r3.
Thebasecaseoccurswhenn1Dn2D0,inwhichcasewehavenowork
todotomergethetwoemptysubarrays.Sincewehaveassumedthatthesub
arrayTp1::r1isatleastaslongasTp2::r2,thatis,n1 n2,wecancheck
forthebasecasebyjustcheckingwhethern1D0.Wemustalsoensurethatthe
recursionproperlyhandlesthecasewhenonlyoneofthetwosubarraysisempty,
which,byourassumptionthatn1 n2,mustbethesubarrayTp2::r2.
Now,let'sputtheseideasintopseudocode.Westartwiththebinarysearch,
whichweexpressserially.TheprocedureBINARYSEARCH.xTpr/takesa
keyxandasubarrayTp::r,anditreturnsoneofthefollowing:
IfTp::risempty(r<p),thenitreturnstheindexp.
IfxTp,andhencelessthanorequaltoalltheelementsofTp::r,then
itreturnstheindexp.
Ifx>Tp,thenitreturnsthelargestindexqintherangep<qrC1such
thatTq1<x.
Hereisthepseudocode:
BINARYSEARCH.xTpr/
1lowDp
2highDmax.prC1/
3whilelow<high
4 midDb.lowChigh/=2c
5 ifxTmid
6 highDmid
7 elselowDmidC1
8returnhigh

Pgina221

800 Chapter27MultithreadedAlgorithms

ThecallBINARYSEARCH.xTpr/takes.lgn/serialtimeintheworstcase,
wherenDr pC1isthesizeofthesubarrayonwhichitruns.(SeeExer
cise2.35.)SinceBINARYSEARCHisaserialprocedure,itsworstcaseworkand
spanareboth.lgn/.

https://translate.googleusercontent.com/translate_f 136/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Wearenowpreparedtowritepseudocodeforthemultithreadedmergingpro
cedureitself.LiketheM ERGEprocedureonpage31,thePMERGEprocedure
assumesthatthetwosubarraystobemergedliewithinthesamearray.NacionesUnidas
likeMERGE,however,PMERGEdoesnotassumethatthetwosubarraysto
bemergedareadjacentwithinthearray.(Thatis,PMERGEdoesnotrequire
thatp2Dr1C1.)AnotherdifferencebetweenMERGEandPMERGEisthat
PMERGEtakesasanargumentanoutputsubarrayAintowhichthemergedval
uesshouldbestored.ThecallPMERGE.Tp1r1p2r2Ap3/mergesthesorted
subarraysTp1::r1andTp2::r2intothesubarrayAp3::r3,wherer3D
p3C.r1 p1C1/C.r2 p2C1/1Dp3C.r1 p1/C.r2 p2/C1and
isnotprovidedasaninput.

PMERGE.Tp1r1p2r2Ap3/
1n1Dr1 p1C1
2n2Dr2 p2C1
3ifn1<n2 //ensurethatn1 n2
4 exchangep1withp2
5 exchanger1withr2
6 exchangen1withn2
7ifn1==0 //bothempty?
8 regreso
9elseq1Dbp1Cr1/=2c
10 q2DBINARYSEARCH.Tq1Tp2r2/
11 q3Dp3C.q1 p1/C.q2 p2/
12 Aq3DTq1
13 spawnPMERGE.Tp1q1 1p2q2 1Ap3/
14 PMERGE.Tq1C1r1q2r2Aq3C1/
15 sync

ThePMERGEprocedureworksasfollows.Lines12computethelengthsn1
andn2ofthesubarraysTp1::r1andTp2::r2,respectively.Lines36en
forcetheassumptionthatn1 n2.Line7testsforthebasecase,wherethe
subarrayTp1::r1isempty(andhencesoisTp2::r2),inwhichcasewesim
plyreturn.Lines915implementthedivideandconquerstrategy.Line9com
putesthemidpointofTp1::r1,andline10findsthepointq2inTp2::r2such
thatallelementsinTp2::q2 1arelessthanTq1(whichcorrespondstox)
andalltheelementsinTq2::p2areatleastaslargeasTq1.Line11com

Pgina222

27.3Multithreadedmergesort 801

putestheindexq3oftheelementthatdividestheoutputsubarrayAp3::r3into
Ap3::q3 1andAq3C1::r3,andthenline12copiesTq1directlyintoAq3.
Then,werecurseusingnestedparallelism.Line13spawnsthefirstsubproblem,
whileline14callsthesecondsubprobleminparallel.Thesyncstatementinline15
ensuresthatthesubproblemshavecompletedbeforetheprocedurereturns.(Since
everyprocedureimplicitlyexecutesasyncbeforereturning,wecouldhaveomitted
thesyncstatementinline15,butincludingitisgoodcodingpractice.)There
issomeclevernessinthecodingtoensurethatwhenthesubarrayTp2::r2is
empty,thecodeoperatescorrectly.Thewayitworksisthatoneachrecursivecall,
amedianelementofTp1::r1isplacedintotheoutputsubarray,untilTp1::r1
itselffinallybecomesempty,triggeringthebasecase.

Analysisofmultithreadedmerging
WefirstderivearecurrenceforthespanPM1.n/ofPMERGE,wherethetwo
subarrayscontainatotalofnDn1Cn2elements.Becausethespawninline13and
thecallinline14operatelogicallyinparallel,weneedexamineonlythecostlierof
thetwocalls.Thekeyistounderstandthatintheworstcase,themaximumnumber
ofelementsineitheroftherecursivecallscanbeatmost3n=4,whichweseeas
Sigue.Becauselines36ensurethatn2n1,itfollowsthatn2D2n2=2
.n1Cn2/=2Dn=2.Intheworstcase,oneofthetworecursivecallsmerges
bn1=2celementsofTp1::r1withalln2elementsofTp2::r2,andhencethe
numberofelementsinvolvedinthecallis
bn1=2cCn2 n1=2Cn2=2Cn2=2
D.n1Cn2/=2Cn2=2
n=2Cn=4
D3n=4:
Addinginthe.lgn/costofthecalltoBINARYSEARCHinline10,weobtain
thefollowingrecurrencefortheworstcasespan:
PM1.n/DPM1.3n=4/C.lgn/: (27.8)
(Forthebasecase,thespanis.1/,sincelines18executeinconstanttime.)
Thisrecurrencedoesnotfallunderanyofthecasesofthemastertheorem,butit
meetstheconditionofExercise4.62.Therefore,thesolutiontorecurrence(27.8)

https://translate.googleusercontent.com/translate_f 137/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
isPM1.n/D.lg2n/.
WenowanalyzetheworkPM1.n/ofPMERGEonnelements,whichturnsout
tobe.n/.SinceeachofthenelementsmustbecopiedfromarrayTtoarrayA,
wehavePM1.n/D.n/.Thus,itremainsonlytoshowthatPM1.n/DOn/.
Weshallfirstderivearecurrencefortheworstcasework.Thebinarysearchin
line10costs.lgn/intheworstcase,whichdominatestheotherworkoutside

Pgina223

802 Chapter27MultithreadedAlgorithms

oftherecursivecalls.Fortherecursivecalls,observethatalthoughtherecursive
callsinlines13and14mightmergedifferentnumbersofelements,togetherthe
tworecursivecallsmergeatmostnelements(actuallyn1elements,sinceTq1
doesnotparticipateineitherrecursivecall).Moreover,aswesawinanalyzingthe
span,arecursivecalloperatesonatmost3n=4elements.Wethereforeobtainthe
reaparicin
PM1.n/DPM1.n/CPM1..1/n/CO.lgn/ (27.9)
whereliesintherange1=43=4,andwhereweunderstandthattheactual
valueofmayvaryforeachlevelofrecursion.
Weprovethatrecurrence(27.9)hassolutionPM1DOn/viathesubstitution
Mtodo.AssumethatPM1.n/c1nc2lgnforsomepositiveconstantsc1andc2.
Substitutinggivesus
PM1.n/.c1nc2lg.n//C.c1.1/nc2lg..1/n//C.lgn/
Dc1.C.1//nc2.lg.n/Clg..1/n//C.lgn/
Dc1nc2.lgClgnClg.1/Clgn/C.lgn/
Dc1nc2lgn.c2.lgnClg..1///.lgn//
c1nc2lgn
sincewecanchoosec2largeenoughthatc2.lgnClg..1///dominatesthe
.lgn/term.Furthermore,wecanchoosec1largeenoughtosatisfythebase
conditionsoftherecurrence.SincetheworkPM1.n/ofPMERGEisboth.n/
andOn/,wehavePM1.n/D.n/.
TheparallelismofPMERGEisPM1.n/=PM1.n/D.n=lg2n/.

Multithreadedmergesort
Nowthatwehaveanicelyparallelizedmultithreadedmergingprocedure,wecan
incorporateitintoamultithreadedmergesort.Thisversionofmergesortissimilar
totheMERGESORT 0procedurewesawearlier,butunlikeMERGESORT 0,ittakes
asanargumentanoutputsubarrayB,whichwillholdthesortedresult.Inpar
ticular,thecallPMERGESORT.AprBs/sortstheelementsinAp::rand
storestheminBs::sCrp.

Page224

27.3Multithreadedmergesort 803

PMERGESORT.AprBs/
1nDrpC1
2ifn==1
3 BsDAp
4elseletT1::nbeanewarray
5 qDbpCr/=2c
6 q0DqpC1
7 spawnPMERGESORT.ApqT1/
8 PMERGESORT.AqC1rTq0C1/
9 sync
10 PMERGE.T1q0q0C1nBs/

Afterline1computesthenumbernofelementsintheinputsubarrayAp::r,
lines23handlethebasecasewhenthearrayhasonly1element.Lines46set
upfortherecursivespawninline7andcallinline8,whichoperateinparallel.En
particular,line4allocatesatemporaryarrayTwithnelementstostoretheresults
https://translate.googleusercontent.com/translate_f 138/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
oftherecursivemergesorting.Line5calculatestheindexqofAp::rtodivide
theelementsintothetwosubarraysAp::qandAqC1::rthatwillbesorted
recursively,andline6goesontocomputethenumberq0ofelementsinthefirst
subarrayAp::q,whichline8usestodeterminethestartingindexinTofwhere
tostorethesortedresultofAqC1::r.Atthatpoint,thespawnandrecursive
callaremade,followedbythesyncinline9,whichforcestheproceduretowait
untilthespawnedprocedureisdone.Finally,line10callsPMERGEtomerge
thesortedsubarrays,nowinT1::q0andTq0C1::n,intotheoutputsubarray
Bs::sCrp.

Analysisofmultithreadedmergesort
WestartbyanalyzingtheworkPMS1.n/ofPMERGESORT,whichisconsider
ablyeasierthananalyzingtheworkofPMERGE.Indeed,theworkisgivenbythe
reaparicin
PMS1.n/D2PMS1.n=2/CPM1.n/
D2PMS1.n=2/C.n/:
Thisrecurrenceisthesameastherecurrence(4.4)forordinaryMERGESORT
fromSection2.3.1andhassolutionPMS1.n/D.nlgn/bycase2ofthemaster
teorema.
WenowderiveandanalyzearecurrencefortheworstcasespanPMS1.n/.Ser
causethetworecursivecallstoPMERGESORTonlines7and8operatelogically
inparallel,wecanignoreoneofthem,obtainingtherecurrence

Pgina225

804 Chapter27MultithreadedAlgorithms

PMS1.n/DPMS1.n=2/CPM1.n/
DPMS1.n=2/C.lg2n/: (27.10)
Asforrecurrence(27.8),themastertheoremdoesnotapplytorecurrence(27.10),
butExercise4.62does.ThesolutionisPMS1.n/D.lg3n/,andsothespanof
PMERGESORTis.lg3n/.
ParallelmerginggivesPMERGESORTasignificantparallelismadvantageover
MERGESORT 0. RecallthattheparallelismofMERGESORT 0,whichcallsthese
rialMERGEprocedure,isonly.lgn/.ForPMERGESORT,theparallelismis
PMS1.n/=PMS1.n/D.nlgn/=.lg3n/
D.n=lg2n/
whichismuchbetterbothintheoryandinpractice.Agoodimplementationin
practicewouldsacrificesomeparallelismbycoarseningthebasecaseinorderto
reducetheconstantshiddenbytheasymptoticnotation.Thestraightforwardway
tocoarsenthebasecaseistoswitchtoanordinaryserialsort,perhapsquicksort,
whenthesizeofthearrayissufficientlysmall.

Exercises

27.31
ExplainhowtocoarsenthebasecaseofPMERGE.

27.32
Insteadoffindingamedianelementinthelargersubarray,asPMERGEdoes,con
sideravariantthatfindsamedianelementofalltheelementsinthetwosorted
subarraysusingtheresultofExercise9.38.Givepseudocodeforanefficient
multithreadedmergingprocedurethatusesthismedianfindingprocedure.Ana
lyzeyouralgorithm.

27.33
Giveanefficientmultithreadedalgorithmforpartitioninganarrayaroundapivot,
asisdonebythePARTITIONprocedureonpage171.Youneednotpartitionthear
rayinplace.Makeyouralgorithmasparallelaspossible.Analyzeyouralgorithm.
(Hint:Youmayneedanauxiliaryarrayandmayneedtomakemorethanonepass
overtheinputelements.)

27.34
GiveamultithreadedversionofRECURSIVEFFTonpage911.Makeyourimple
mentationasparallelaspossible.Analyzeyouralgorithm.

Pgina226

https://translate.googleusercontent.com/translate_f 139/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

ProblemsforChapter27 805

27.35?
GiveamultithreadedversionofRANDOMIZEDSELECTonpage216.Makeyour
implementationasparallelaspossible.Analyzeyouralgorithm.(Hint:Usethe
partitioningalgorithmfromExercise27.33.)

27.36?
ShowhowtomultithreadSELECTfromSection9.3.Makeyourimplementationas
parallelaspossible.Analyzeyouralgorithm.

Problemas

271Implementingparallelloopsusingnestedparallelism
Considerthefollowingmultithreadedalgorithmforperformingpairwiseaddition
onnelementarraysA1::nandB1::n,storingthesumsinC1::n:

SUMARRAYS.ABC/
1parallelforiD1toA:length
2 CiDAiCBi

a.RewritetheparallelloopinSUMARRAYSusingnestedparallelism(spawn
andsync)inthemannerofMATVECMAINLOOP.Analyzetheparallelism
ofyourimplementation.

Considerthefollowingalternativeimplementationoftheparallelloop,which
containsavaluegrainsizetobespecified:

SUMARRAYS 0.ABC/
1nDA:length
2grainsizeD //tobedetermined
3rDdn=grainsizee
4forkD0tor1
5 spawnADDSUBARRAY.ABCkgrainsizeC1
min..kC1/grainsizen//
6sync

ADDSUBARRAY.ABCij/
1forkDitoj
2 CkDAkCBk

Pgina227

806 Chapter27MultithreadedAlgorithms

segundo.SupposethatwesetgrainsizeD1.Whatistheparallelismofthisimplemen
tation?

do.GiveaformulaforthespanofSUMARRAYS 0intermsofnandgrainsize.
Derivethebestvalueforgrainsizetomaximizeparallelism.

272Savingtemporaryspaceinmatrixmultiplication
ThePMATRIXMULTIPLYRECURSIVEprocedurehasthedisadvantagethatit
mustallocateatemporarymatrixTofsizenn,whichcanadverselyaffectthe
constantshiddenbythenotation.ThePMATRIXMULTIPLYRECURSIVEpro
ceduredoeshavehighparallelism,however.Forexample,ignoringtheconstants
inthenotation,theparallelismformultiplying10001000matricescomesto
approximately10003=102D107,sincelg1000 10.Mostparallelcomputers
havefarfewerthan10millionprocessors.

a.Describearecursivemultithreadedalgorithmthateliminatestheneedforthe
temporarymatrixTatthecostofincreasingthespanto.n/.(Hint:Com
puteCDCCABfollowingthegeneralstrategyofPMATRIXMULTIPLY
RECURSIVE,butinitializeCinparallelandinsertasyncinajudiciouslycho
senlocation.)

segundo.Giveandsolverecurrencesfortheworkandspanofyourimplementation.

do.Analyzetheparallelismofyourimplementation.Ignoringtheconstantsinthe
notation,estimatetheparallelismon10001000matrices.Comparewith
theparallelismofPMATRIXMULTIPLYRECURSIVE.

https://translate.googleusercontent.com/translate_f 140/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
273Multithreadedmatrixalgorithms
a.ParallelizetheLUDECOMPOSITIONprocedureonpage821bygivingpseu
docodeforamultithreadedversionofthisalgorithm.Makeyourimplementa
tionasparallelaspossible,andanalyzeitswork,span,andparallelism.

segundo.DothesameforLUPDECOMPOSITIONonpage824.

do.DothesameforLUPSOLVEonpage817.

re.Dothesameforamultithreadedalgorithmbasedonequation(28.13)forin
vertingasymmetricpositivedefinitematrix.

Pgina228

ProblemsforChapter27 807

274Multithreadingreductionsandprefixcomputations
Areductionofanarrayx1::n,whereisanassociativeoperator,isthevalue
yDx1x2xn:
Thefollowingprocedurecomputesthereductionofasubarrayxi::jserially.

REDUCE.xij/
1yDxi
2forkDiC1toj
3 yDyxk
4returny

a.UsenestedparallelismtoimplementamultithreadedalgorithmPREDUCE,
whichperformsthesamefunctionwith.n/workand.lgn/span.Analizar
youralgorithm.

Arelatedproblemisthatofcomputingaprefixcomputation,sometimes
calledascan,onanarrayx1::n,whereisonceagainanassociativeop
erator.Thescanproducesthearrayy1::ngivenby
y1Dx1
y2Dx1x2
y3Dx1x2x3
Unesdoc.unesco.orgunesdoc.unesco.org

ynDx1x2x3xn
thatis,allprefixesofthearrayxsummedusingtheoperator.Thefollowing
serialprocedureSCANperformsaprefixcomputation:

SCAN.x/
1nDx:length
2lety1::nbeanewarray
3y1Dx1
4foriD2ton
5 yiDyi1xi
6returny

Unfortunately,multithreadingSCANisnotstraightforward.Forexample,changing
theforlooptoaparallelforloopwouldcreateraces,sinceeachiterationofthe
loopbodydependsonthepreviousiteration.ThefollowingprocedurePSCAN1
performstheprefixcomputationinparallel,albeitinefficiently:

Page229

808 Chapter27MultithreadedAlgorithms

PSCAN1.x/
1nDx:length
2lety1::nbeanewarray
3PSCAN1AUX.xY1n/
4returny

PSCAN1AUX.xyij/

https://translate.googleusercontent.com/translate_f 141/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
1parallelforlDitoj
2 ylDPREDUCE.x1l/

segundo.Analyzethework,span,andparallelismofPSCAN1.

Byusingnestedparallelism,wecanobtainamoreefficientprefixcomputa
tion:

PSCAN2.x/
1nDx:length
2lety1::nbeanewarray
3PSCAN2AUX.xY1n/
4returny

PSCAN2AUX.xyij/
1ifi==j
2 yiDxi
3elsekDbiCj/=2c
4 spawnPSCAN2AUX.xyik/
5 PSCAN2AUX.xykC1j/
6 sync
7 parallelforlDkC1toj
8 ylDykyl

do.ArguethatPSCAN2iscorrect,andanalyzeitswork,span,andparallelism.

WecanimproveonbothPSCAN1andPSCAN2byperformingtheprefix
computationintwodistinctpassesoverthedata.Onthefirstpass,wegatherthe
termsforvariouscontiguoussubarraysofxintoatemporaryarrayt,andonthe
secondpassweusethetermsinttocomputethefinalresulty.Thefollowing
pseudocodeimplementsthisstrategy,butcertainexpressionshavebeenomitted:

Pgina230

ProblemsforChapter27 809

PSCAN3.x/
1nDx:length
2lety1::nandt1::nbenewarrays
3y1Dx1
4ifn>1
5 PSCANUP.xt2n/
6 PSCANDOWN.x1xtY2n/
7returny

PSCANUP.xtij/
1ifi==j
2 returnxi
3else
4 kDbiCj/=2c
5 tkDspawnPSCANUP.xtik/
6 rightDPSCANUP.xtkC1j/
7 sync
8 regreso //fillintheblank

PSCANDOWN.xtyij/
1ifi==j
2 yiDxi
3else
4 kDbiCj/=2c
5 spawnPSCANDOWN. xtyik///fillintheblank
6 PSCANDOWN. xtykC1j/ //fillintheblank
7 sync

re.Fillinthethreemissingexpressionsinline8ofPSCANUPandlines5and6
ofPSCANDOWN.Arguethatwithexpressionsyousupplied,PSCAN3is
correcto.(Hint:ProvethatthevaluepassedtoPSCANDOWN.xtyij/
satisfiesDx1x2xi1.)

mi.Analyzethework,span,andparallelismofPSCAN3.

275Multithreadingasimplestencilcalculation
Computationalscienceisrepletewithalgorithmsthatrequiretheentriesofanarray
tobefilledinwithvaluesthatdependonthevaluesofcertainalreadycomputed

https://translate.googleusercontent.com/translate_f 142/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
neighboringentries,alongwithotherinformationthatdoesnotchangeoverthe
courseofthecomputation.Thepatternofneighboringentriesdoesnotchange
duringthecomputationandiscalledastencil.Forexample,Section15.4presents

Pgina231

810 Chapter27MultithreadedAlgorithms

astencilalgorithmtocomputealongestcommonsubsequence,wherethevaluein
entrycijdependsonlyonthevaluesinci1j,cij1,andci1j1,
aswellastheelementsxiandyjwithinthetwosequencesgivenasinputs.El
inputsequencesarefixed,butthealgorithmfillsinthetwodimensionalarraycso
thatitcomputesentrycijaftercomputingallthreeentriesci1j,cij1,
andci1J 1.
Inthisproblem,weexaminehowtousenestedparallelismtomultithreada
simplestencilcalculationonannnarrayAinwhich,ofthevaluesinA,the
valueplacedintoentryAijdependsonlyonvaluesinAi0j0,wherei0i
andj0j(andofcourse,i0iorj0j).Inotherwords,thevalueinan
entrydependsonlyonvaluesinentriesthatareaboveitand/ortoitsleft,along
withstaticinformationoutsideofthearray.Furthermore,weassumethroughout
thisproblemthatoncewehavefilledintheentriesuponwhichAijdepends,we
canfillinAijin.1/time(asintheLCSLENGTHprocedureofSection15.4).
WecanpartitionthennarrayAintofourn=2n=2subarraysasfollows:
UN UN
A11 A12
ANUNCIO : (27.11)
A21 A22
ObservenowthatwecanfillinsubarrayA11recursively,sinceitdoesnotdepend
ontheentriesoftheotherthreesubarrays.OnceA11iscomplete,wecancontinue
tofillinA12andA21recursivelyinparallel,becausealthoughtheybothdepend
onA11,theydonotdependoneachother.Finally,wecanfillinA22recursively.

a.Givemultithreadedpseudocodethatperformsthissimplestencilcalculation
usingadivideandconqueralgorithmSIMPLESTENCILbasedonthedecom
position(27.11)andthediscussionabove.(Don'tworryaboutthedetailsofthe
basecase,whichdependsonthespecificstencil.)Giveandsolverecurrences
fortheworkandspanofthisalgorithmintermsofn.Whatistheparallelism?

segundo.Modifyyoursolutiontopart(a)todivideannnarrayintoninen=3n=3
subarrays,againrecursingwithasmuchparallelismaspossible.Analyzethis
algoritmo.Howmuchmoreorlessparallelismdoesthisalgorithmhavecom
paredwiththealgorithmfrompart(a)?

do.Generalizeyoursolutionstoparts(a)and(b)asfollows.Chooseaninteger
segundo
2.Divideannnarrayintob2subarrays,eachofsizen=bn=b,recursing
withasmuchparallelismaspossible.Intermsofnandb,whatarethework,
span,andparallelismofyouralgorithm?Arguethat,usingthisapproach,the
parallelismmustbeon/foranychoiceofb 2.(Hint:Forthislastargument,
showthattheexponentofnintheparallelismisstrictlylessthan1forany
choiceofb 2

Pgina232

NotesforChapter27 811

re.Givepseudocodeforamultithreadedalgorithmforthissimplestencilcalcu
lationthatachieves.n=lgn/parallelism.Argueusingnotionsofworkand
spanthattheproblem,infact,has.n/inherentparallelism.Asitturnsout,
thedivideandconquernatureofourmultithreadedpseudocodedoesnotletus
achievethismaximalparallelism.

276Randomizedmultithreadedalgorithms
Justaswithordinaryserialalgorithms,wesometimeswanttoimplementrandom
izedmultithreadedalgorithms.Thisproblemexploreshowtoadaptthevarious
performancemeasuresinordertohandletheexpectedbehaviorofsuchalgorithms.
Italsoasksyoutodesignandanalyzeamultithreadedalgorithmforrandomized
quicksort.

a.Explainhowtomodifytheworklaw(27.2),spanlaw(27.3),andgreedysched
ulerbound(27.4)toworkwithexpectationswhenTP,T1,andT1areallran
domvariables.

segundo.Considerarandomizedmultithreadedalgorithmforwhich1%ofthetimewe
haveT1D104andT10000D1,butfor99%ofthetimewehaveT1D

https://translate.googleusercontent.com/translate_f 143/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
T 10000D109.Arguethatthespeedupofarandomizedmultithreadedalgo
rithmshouldbedefinedasET 1=ETP,ratherthanET1=TP.

do.Arguethattheparallelismofarandomizedmultithreadedalgorithmshouldbe
definedastheratioET1=ET1.

re.MultithreadtheRANDOMIZEDQUICKSORTalgorithmonpage179byusing
nestedparallelism.(DonotparallelizeRANDOMIZEDPARTITION.)Givethe
pseudocodeforyourPRANDOMIZEDQUICKSORTalgorithm.

mi.Analyzeyourmultithreadedalgorithmforrandomizedquicksort.(Hint:Re
viewtheanalysisofRANDOMIZEDSELECTonpage216.)

Chapternotes

Parallelcomputers,modelsforparallelcomputers,andalgorithmicmodelsforpar
allelprogramminghavebeenaroundinvariousformsforyears.Prioreditionsof
thisbookincludedmaterialonsortingnetworksandthePRAM(ParallelRandom
AccessMachine)model.Thedataparallelmodel[48,168]isanotherpopularal
gorithmicprogrammingmodel,whichfeaturesoperationsonvectorsandmatrices
asprimitives.

Pgina233

812 Chapter27MultithreadedAlgorithms

Graham[149]andBrent[55]showedthatthereexistschedulersachievingthe
boundofTheorem27.1.Eager,Zahorjan,andLazowska[98]showedthatany
greedyschedulerachievesthisboundandproposedthemethodologyofusingwork
andspan(althoughnotbythosenames)toanalyzeparallelalgorithms.Blelloch
[47]developedanalgorithmicprogrammingmodelbasedonworkandspan(which
hecalledthedepthofthecomputation)fordataparallelprogramming.Blumofe
andLeiserson[52]gaveadistributedschedulingalgorithmfordynamicmulti
threadingbasedonrandomizedworkstealingandshowedthatitachievesthe
boundETPT1=PCOT1/.Arora,Blumofe,andPlaxton[19]andBlelloch,
Gibbons,andMatias[49]alsoprovidedprovablygoodalgorithmsforscheduling
dynamicmultithreadedcomputations.
Themultithreadedpseudocodeandprogrammingmodelwereheavilyinfluenced
bytheCilk[51,118]projectatMITandtheCilk++[71]extensionstoC++dis
tributedbyCilkArts,Inc.Manyofthemultithreadedalgorithmsinthischapter
appearedinunpublishedlecturenotesbyCELeisersonandH.Prokopandhave
beenimplementedinCilkorCilk++.Themultithreadedmergesortingalgorithm
wasinspiredbyanalgorithmofAkl[12].
ThenotionofsequentialconsistencyisduetoLamport[223].

Pgina234

https://translate.googleusercontent.com/translate_f 144/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

28 MatrixOperations

Becauseoperationsonmatriceslieattheheartofscientificcomputing,efficiental
gorithmsforworkingwithmatriceshavemanypracticalapplications.Thischapter
focusesonhowtomultiplymatricesandsolvesetsofsimultaneouslinearequa
Ciones.AppendixDreviewsthebasicsofmatrices.
Section28.1showshowtosolveasetoflinearequationsusingLUPdecomposi
Ciones.Then,Section28.2exploresthecloserelationshipbetweenmultiplyingand
invertingmatrices.Finally,Section28.3discussestheimportantclassofsymmetric
positivedefinitematricesandshowshowwecanusethemtofindaleastsquares
solutiontoanoverdeterminedsetoflinearequations.
Oneimportantissuethatarisesinpracticeisnumericalstability.Duetothe
limitedprecisionoffloatingpointrepresentationsinactualcomputers,roundoff
errorsinnumericalcomputationsmaybecomeamplifiedoverthecourseofacom
putation,leadingtoincorrectresultswecallsuchcomputationsnumericallyun
stable.Althoughweshallbrieflyconsidernumericalstabilityonoccasion,wedo
notfocusonitinthischapter.WereferyoutotheexcellentbookbyGoluband
VanLoan[144]forathoroughdiscussionofstabilityissues.

28.1Solvingsystemsoflinearequations

Numerousapplicationsneedtosolvesetsofsimultaneouslinearequations.Nosotros
canformulatealinearsystemasamatrixequationinwhicheachmatrixorvector
elementbelongstoafield,typicallytherealnumbersR.Thissectiondiscusseshow
tosolveasystemoflinearequationsusingamethodcalledLUPdecomposition.
Westartwithasetoflinearequationsinnunknownsx1x2:::xn:

Pgina235

814 Chapter28MatrixOperations

a11x1Ca12x2CCa1nxn Db1
a21x1Ca22x2CCa2nxn Db2
Unesdoc.unesco.orgunesdoc.unesco.org (28.1)

an1x1Can2x2CCannxn Dbn:
Asolutiontotheequations(28.1)isasetofvaluesforx1x2:::xnthatsatisfy
alloftheequationssimultaneously.Inthissection,wetreatonlythecaseinwhich
thereareexactlynequationsinnunknowns.
Wecanconvenientlyrewriteequations(28.1)asthematrixvectorequation

a11 a12 a1n x1 b1


a21 a22 a2n x2 b2
re
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
an1 an2 ann xn bn
or,equivalently,lettingAD.aij/,xD.xi/,andbD.bi/,as
AxDb: (28.2)
IfAisnonsingular,itpossessesaninverseA1,and
xDA1b (28.3)
isthesolutionvector.Wecanprovethatxistheuniquesolutiontoequation(28.2)
comosigue.Iftherearetwosolutions,xandx0,thenAxDAx0Dband,lettingI
denoteanidentitymatrix,
xDIx
D.A1A/x
DA1.Ax/
DA1.Ax0/
D.A1A/x0

https://translate.googleusercontent.com/translate_f 145/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Dx0:
Inthissection,weshallbeconcernedpredominantlywiththecaseinwhichA
isnonsingularor,equivalently(byTheoremD.1),therankofAisequaltothe
numbernofunknowns.Thereareotherpossibilities,however,whichmeritabrief
discussion.Ifthenumberofequationsislessthanthenumbernofunknownsor,
moregenerally,iftherankofAislessthannthenthesystemisunderdeter
mined.Anunderdeterminedsystemtypicallyhasinfinitelymanysolutions,al
thoughitmayhavenosolutionsatalliftheequationsareinconsistent.Siel
numberofequationsexceedsthenumbernofunknowns,thesystemisoverdeter
mined,andtheremaynotexistanysolutions.Section28.3addressestheimportant

Pgina236

28.1Solvingsystemsoflinearequations 815

problemoffindinggoodapproximatesolutionstooverdeterminedsystemsoflinear
Ecuaciones.
LetusreturntoourproblemofsolvingthesystemAxDbofnequationsinn
DesconocidosWecouldcomputeA1andthen,usingequation(28.3),multiplyb
byA1,yieldingxDA1b.Thisapproachsuffersinpracticefromnumerical
instability.Fortunately,anotherapproachLUPdecompositionisnumerically
stableandhasthefurtheradvantageofbeingfasterinpractice.

OverviewofLUPdecomposition
TheideabehindLUPdecompositionistofindthreennmatricesL,U,andP
suchthat
PADLU (28.4)
dnde
Lisaunitlowertriangularmatrix,
Uisanuppertriangularmatrix,and
Pisapermutationmatrix.
WecallmatricesL,U,andPsatisfyingequation(28.4)anLUPdecomposition
ofthematrixA.WeshallshowthateverynonsingularmatrixApossessessucha
decomposition.
ComputinganLUPdecompositionforthematrixAhastheadvantagethatwe
canmoreeasilysolvelinearsystemswhentheyaretriangular,asisthecasefor
bothmatricesLandU.OncewehavefoundanLUPdecompositionforA,we
cansolveequation(28.2),AxDb,bysolvingonlytriangularlinearsystems,as
Sigue.MultiplyingbothsidesofAxDbbyPyieldstheequivalentequation
PAxDPb,which,byExerciseD.14,amountstopermutingtheequations(28.1).
Usingourdecomposition(28.4),weobtain
LUxDPb:
Wecannowsolvethisequationbysolvingtwotriangularlinearsystems.Nosdeja
defineyDUx,wherexisthedesiredsolutionvector.First,wesolvethelower
triangularsystem
LyDPb (28.5)

fortheunknownvectorybyamethodcalledforwardsubstitution.Havingsolved
fory,wethensolvetheuppertriangularsystem
UxDy (28,6)

Pgina237

816 Chapter28MatrixOperations

fortheunknownxbyamethodcalledbacksubstitution.Becausethepermu
tationmatrixPisinvertible(ExerciseD.23),multiplyingbothsidesofequa
tion(28.4)byP1givesP1PADP1LU,sothat
ADP1LU: (28.7)
Hence,thevectorxisoursolutiontoAxDb:
AxDP1LUx(byequation(28.7))
DP1Ly (byequation(28.6))
DP1Pb (byequation(28.5))

https://translate.googleusercontent.com/translate_f 146/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Db:
Ournextstepistoshowhowforwardandbacksubstitutionworkandthenattack
theproblemofcomputingtheLUPdecompositionitself.

Forwardandbacksubstitution

Forwardsubstitutioncansolvethelowertriangularsystem(28.5)in.n2/time,
givenL,P,andb.Forconvenience,werepresentthepermutationPcompactly
byanarray1::n.ForiD12:::n,theentryiindicatesthatPiiD1
andPijD0forji.Thus,PAhasaijinrowiandcolumnj,andPb
hasbiasitsithelement.SinceLisunitlowertriangular,wecanrewriteequa
tion(28.5)as
y1 Db1
l21y1C y2 Db2
l31y1Cl32y2C y3 Db3
Unesdoc.unesco.orgunesdoc.unesco.org

ln1y1Cln2y2Cln3y3CCyn Dbn:
Thefirstequationtellsusthaty1Db1.Knowingthevalueofy1,wecan
substituteitintothesecondequation,yielding
y2Db2 l21y1:
Now,wecansubstitutebothy1andy2intothethirdequation,obtaining
y3Db3 .l31y1Cl32y2/:
Ingeneral,wesubstitutey1y2:::yi1forwardintotheithequationtosolve
foryi:

Pgina238

28.1Solvingsystemsoflinearequations 817

xi1
yiDbi lijyj:
jD1
Havingsolvedfory,wesolveforxinequation(28.6)usingbacksubstitution,
whichissimilartoforwardsubstitution.Here,wesolvethenthequationfirstand
workbackwardtothefirstequation.Likeforwardsubstitution,thisprocessruns
in.n2/time.SinceUisuppertriangular,wecanrewritethesystem(28.6)as
u11x1Cu12x2CCu1n2xn2Cu1n1xn1C u1nxnDy1
u22x2CCu2n2xn2Cu2n1xn1C u2nxnDy2
Unesdoc.unesco.orgunesdoc.unesco.org

un2n2xn2Cun2n1xn1Cun2nxnDyn2
un1n1xn1Cun1nxnDyn1
unnxnDyn:
Thus,wecansolveforxnxn1:::x1successivelyasfollows:
xn Dyn=unn
xn1 D.yn1 un1nxn/=un1n1
xn2 D.yn2 .un2n1xn1Cun2nxn//=un2n2
Unesdoc.unesco.orgunesdoc.unesco.org

or,ingeneral,
!
xnorte
xiDyi uijxj =uii:
jDiC1
GivenP,L,U,andb,theprocedureLUPSOLVEsolvesforxbycombining
forwardandbacksubstitution.Thepseudocodeassumesthatthedimensionnap
pearsintheattributeL:rowsandthatthepermutationmatrixPisrepresentedby
thearray.

LUPSOLVE.LUb/
1nDL:rows
2letxbeanewvectoroflengthn
3foriD1ton Pi1
4 yiDbi
jD1lijyj
5foriDndownto1Pn
6 xiDyi jDiC1uijxj=uii
7returnx

https://translate.googleusercontent.com/translate_f 147/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina239

818 Chapter28MatrixOperations

ProcedureLUPSOLVEsolvesforyusingforwardsubstitutioninlines34,and
thenitsolvesforxusingbackwardsubstitutioninlines56.Sincethesummation
withineachoftheforloopsincludesanimplicitloop,therunningtimeis.n2/.
Asanexampleofthesemethods,considerthesystemoflinearequationsdefined
por
120 3
344 xD 7
563 8
dnde
120
ANUNCIO344
563
3
bD 7
8
andwewishtosolvefortheunknownx.TheLUPdecompositionis
1 00
LD 0:2 10
0:60:51
5 6 3
UD 00:8 0:6
0 0 2:5
001
PD 100 :
010
(YoumightwanttoverifythatPADLU.)Usingforwardsubstitution,wesolve
LyDPbfory:
1 00 y1 8
0:2 10 y2 re 3
0:60:51 y3 7
obtaining
8
yD 1:4
1:5
bycomputingfirsty1,theny2,andfinallyy3.Usingbacksubstitution,wesolve
UxDyforx:

Pgina240

28.1Solvingsystemsoflinearequations 819

5 6 3 x1 8
00:8 0:6 x2 re 1:4
0 0 2:5 x3 1:5
therebyobtainingthedesiredanswer
1:4
xD 2:2
0:6
bycomputingfirstx3,thenx2,andfinallyx1.

ComputinganLUdecomposition

WehavenowshownthatifwecancreateanLUPdecompositionforanonsingular
matrixA,thenforwardandbacksubstitutioncansolvethesystemAxDbof
linearequations.NowweshowhowtoefficientlycomputeanLUPdecomposition
forA.WestartwiththecaseinwhichAisannnnonsingularmatrixandPis
absent(or,equivalently,PDIn).Inthiscase,wefactorADLU.Wecallthe
twomatricesLandUanLUdecompositionofA.
WeuseaprocessknownasGaussianeliminationtocreateanLUdecomposi
Cin.Westartbysubtractingmultiplesofthefirstequationfromtheotherequations
inordertoremovethefirstvariablefromthoseequations.Then,wesubtractmul
tiplesofthesecondequationfromthethirdandsubsequentequationssothatnow

https://translate.googleusercontent.com/translate_f 148/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
thefirstandsecondvariablesareremovedfromthem.Wecontinuethisprocess
untilthesystemthatremainshasanuppertriangularforminfact,itisthema
trixU.ThematrixLismadeupoftherowmultipliersthatcausevariablestobe
Eliminado.
Ouralgorithmtoimplementthisstrategyisrecursive.Wewishtoconstructan
LUdecompositionforannnnonsingularmatrixA.IfnD1,thenwearedone,

sincewecanchooseLDI 1andUDA.Forn>1,webreakAintofourparts:

a11 a12 a1n


a21 a22 a2n
ANUNCIO Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
an1 an2 ann
UN UN
a11 wT
re
A0

dnde isacolumn.n 1/vector,wTisarow.n 1/vector,andA0isan


.norte1/ .norte1/matrix.Then,usingmatrixalgebra(verifytheequationsby

Page241

820 Chapter28MatrixOperations

simplymultiplyingthrough),wecanfactorAas
UN UN
a11 wT
ANUNCIO
A0
UN UN
1 0 a11 wT
re : (28,8)
=a11 In1 0A0 wT=a11
The0sinthefirstandsecondmatricesofequation(28.8)arerowandcol
umn.n1/vectors,respectively.ThetermwT=a11,formedbytakingthe
outerproductof andwanddividingeachelementoftheresultbya11,isan
.n1/.n1/matrix,whichconformsinsizetothematrixA0fromwhichitis
RestadoTheresulting.n1/.n1/matrix
A0 wT=a11 (28.9)
iscalledtheSchurcomplementofAwithrespecttoa11.
WeclaimthatifAisnonsingular,thentheSchurcomplementisnonsingular,
too.Porqu?SupposethattheSchurcomplement,whichis.n 1/.n 1/,is
singular.ThenbyTheoremD.1,ithasrowrankstrictlylessthann1.Because
thebottomn1entriesinthefirstcolumnofthematrix
UN UN
a11 wT
0A0 wT=a11
areall0,thebottomn 1rowsofthismatrixmusthaverowrankstrictlyless
thann 1.Therowrankoftheentirematrix,therefore,isstrictlylessthann.
ApplyingExerciseD.28toequation(28.8),Ahasrankstrictlylessthann,and
fromTheoremD.1wederivethecontradictionthatAissingular.
BecausetheSchurcomplementisnonsingular,wecannowrecursivelyfindan
LUdecompositionforit.Letussaythat
A0 wT=a11DL0U0
whereL0isunitlowertriangularandU0isuppertriangular.Then,usingmatrix
algebra,wehave
UN UN
1 0 a11 wT
ANUNCIO
=a11 In1 0A0 wT=a11
UN UN
1 0 a11 wT
re
=a11 In1 0L0U0
UN UN
1 0 a11 wT
re
=a11 L0 0 U0
DLU
therebyprovidingourLUdecomposition.(NotethatbecauseL0isunitlower
triangular,soisL,andbecauseU0isuppertriangular,soisU.)

Pgina242

28.1Solvingsystemsoflinearequations 821

Ofcourse,ifa11D0,thismethoddoesn'twork,becauseitdividesby0.Italso
doesn'tworkiftheupperleftmostentryoftheSchurcomplementA0 wT=a11
is0,sincewedividebyitinthenextstepoftherecursion.Theelementsby

https://translate.googleusercontent.com/translate_f 149/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
whichwedivideduringLUdecompositionarecalledpivots,andtheyoccupythe
diagonalelementsofthematrixU.ThereasonweincludeapermutationmatrixP
duringLUPdecompositionisthatitallowsustoavoiddividingby0.Whenweuse
permutationstoavoiddivisionby0(orbysmallnumbers,whichwouldcontribute
tonumericalinstability),wearepivoting.
AnimportantclassofmatricesforwhichLUdecompositionalwaysworkscor
rectlyistheclassofsymmetricpositivedefinitematrices.Suchmatricesrequire
nopivoting,andthuswecanemploytherecursivestrategyoutlinedabovewith
outfearofdividingby0.Weshallprovethisresult,aswellasseveralothers,in
Section28.3.
OurcodeforLUdecompositionofamatrixAfollowstherecursivestrategy,ex
ceptthataniterationloopreplacestherecursion.(Thistransformationisastandard
optimizationforatailrecursiveprocedureonewhoselastoperationisarecur
sivecalltoitself.SeeProblem74.)ItassumesthattheattributeA:rowsgives
thedimensionofA.WeinitializethematrixUwith0sbelowthediagonaland
matrixLwith1sonitsdiagonaland0sabovethediagonal.

LUDECOMPOSITION.A/
1nDA:rows
2letLandUbenewnnmatrices
3initializeUwith0sbelowthediagonal
4initializeLwith1sonthediagonaland0sabovethediagonal
5forkD1ton
6 ukkDakk
7 foriDkC1ton
8 likDaik=ukk //likholdsi
9 ukiDaki //ukiholdswT yo
10 foriDkC1ton
11 forjDkC1ton
12 aijDaij likukj
13returnLandU

Theouterforloopbeginninginline5iteratesonceforeachrecursivestep.Dentro
thisloop,line6determinesthepivottobeukkDakk.Theforloopinlines79
(whichdoesnotexecutewhenkDn),usestheandwTvectorstoupdateL
andU.Line8determinestheelementsofthevector,storingiinlik,andline9
computestheelementsofthewTvector,storingwT iinuki.Finally,lines1012
computetheelementsoftheSchurcomplementandstorethembackintothema

Pgina243

822 Chapter28MatrixOperations

2315 2 315 2315 2315


613519 3424 3 4 24 3424
2191023 116918 1412 14 1 2
4101131 24921 21717 2173
(un) (segundo) (do) (re)

23 1 5 1000 2315
613519 re 3100 0424
2191023 1410 0012
4101131 2171 0003
UN L Tu
(mi)

Figure28.1TheoperationofLUDECOMPOSITION.(a)ThematrixA.(b)Theelementa11D2
intheblackcircleisthepivot,theshadedcolumnis=a11,andtheshadedrowiswT.Theelements
ofUcomputedthusfarareabovethehorizontalline,andtheelementsofLaretotheleftofthe
lineavertical.TheSchurcomplementmatrixA wT=a
0 11occupiesthelowerright.(c)Wenow

operateontheSchurcomplementmatrixproducedfrompart(b).Theelementa22D4intheblack
circleisthepivot,andtheshadedcolumnandroware=a22andwT(inthepartitioningoftheSchur
complement),respectively.LinesdividethematrixintotheelementsofUcomputedsofar(above),
theelementsofLcomputedsofar(left),andthenewSchurcomplement(lowerright).(d)Afterthe
nextstep,thematrixAisfactored.(Theelement3inthenewSchurcomplementbecomespartofU
whentherecursionterminates.)(e)ThefactorizationADLU.

trixA.(Wedon'tneedtodividebyakkinline12becausewealreadydidsowhen
wecomputedlikinline8.)Becauseline12istriplynested,LUDECOMPOSITION
runsintime.n3/.
Figure28.1illustratestheoperationofLUDECOMPOSITION.Itshowsastan
dardoptimizationoftheprocedureinwhichwestorethesignificantelementsofL
andUinplaceinthematrixA.Thatis,wecansetupacorrespondencebetween
eachelementaijandeitherlij(ifi>j)oruij(ifij)andupdatethema
trixAsothatitholdsbothLandUwhentheprocedureterminates.Paraobtener
thepseudocodeforthisoptimizationfromtheabovepseudocode,justreplaceeach
referencetolorubyayoucaneasilyverifythatthistransformationpreserves

https://translate.googleusercontent.com/translate_f 150/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
exactitud.

ComputinganLUPdecomposition
Generally,insolvingasystemoflinearequationsAxDb,wemustpivotonoff
diagonalelementsofAtoavoiddividingby0.Dividingby0would,ofcourse,
bedisastrous.ButwealsowanttoavoiddividingbyasmallvalueevenifAis

Pgina244

28.1Solvingsystemsoflinearequations 823

nonsingularbecausenumericalinstabilitiescanresult.Wethereforetrytopivot
onalargevalue.
ThemathematicsbehindLUPdecompositionissimilartothatofLUdecom
position.RecallthatwearegivenannnnonsingularmatrixA,andwewish
tofindapermutationmatrixP,aunitlowertriangularmatrixL,andanupper
triangularmatrixUsuchthatPADLU.BeforewepartitionthematrixA,aswe
didforLUdecomposition,wemoveanonzeroelement,sayak1,fromsomewhere
inthefirstcolumntothe.11/positionofthematrix.Fornumericalstability,we
chooseak1astheelementinthefirstcolumnwiththegreatestabsolutevalue.(The
firstcolumncannotcontainonly0s,forthenAwouldbesingular,becauseitsde
terminantwouldbe0,byTheoremsD.4andD.5.)Inordertopreservethesetof
equations,weexchangerow1withrowk,whichisequivalenttomultiplyingAby
apermutationmatrixQontheleft(ExerciseD.14).Thus,wecanwriteQAas
UN UN
ak1 wT
QAD
A0

dnde D.a21a31:::an1/T,exceptthata11replacesak1wTD.ak2ak3
:::akn/andA0isan.n1/.n1/matrix.Sinceak10,wecannowperform
muchthesamelinearalgebraasforLUdecomposition,butnowguaranteeingthat
wedonotdivideby0:
UN UN
ak1 wT
QAD
A0
UN UN
1 0 ak1 wT
re :
=ak1 In1 0A0 wT=ak1
AswesawforLUdecomposition,ifAisnonsingular,thentheSchurcomple
mentA0 wT=ak1isnonsingular,too.Therefore,wecanrecursivelyfindan
LUPdecompositionforit,withunitlowertriangularmatrixL0,uppertriangular
matrixU0,andpermutationmatrixP0,suchthat
P0.A0 wT=ak1/DL0U0:
Define
UN UN
10
PD Q
0P0
whichisapermutationmatrix,sinceitistheproductoftwopermutationmatrices
(ExerciseD.14).Wenowhave

Pgina245

824 Chapter28MatrixOperations
UN UN
10
PAD QA
0P0
UN UN
10 1 0 ak1 wT
re
0P0 =ak1 In1 0A0 wT=ak1
UN UN
1 0 ak1 wT
re
P0=ak1 P0 0A0 wT=ak1
UN UN
1 0 ak1 wT
re
P0=ak1 In1 0P0.A0 wT=ak1/
UN UN
1 0 ak1 wT
re
P0=ak1 In1 0L0U0
UN UN
1 0 ak1 wT
re
P0=ak1 L0 0 U0
DLU
https://translate.googleusercontent.com/translate_f 151/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

yieldingtheLUPdecomposition.BecauseL0isunitlowertriangular,soisL,and
becauseU0isuppertriangular,soisU.
Noticethatinthisderivation,unliketheoneforLUdecomposition,wemust
multiplyboththecolumnvector=ak1andtheSchurcomplementA0 wT=ak1
bythepermutationmatrixP0.HereisthepseudocodeforLUPdecomposition:

LUPDECOMPOSITION.A/
1nDA:rows
2let1::nbeanewarray
3foriD1ton
4 iDi
5forkD1ton
6 pD0
7 foriDkton
8 ifjaikj>p
9 pDjaikj
10 k0Di
11 ifp==0
12 errorsingularmatrix
13 exchangekwithk0
14 foriD1ton
15 exchangeakiwithak i
0

diecisis foriDkC1ton
17 aikDaik=akk
18 forjDkC1ton
19 aijDaij aikakj

Pgina246

28.1Solvingsystemsoflinearequations 825

LikeLUDECOMPOSITION,ourLUPDECOMPOSITIONprocedurereplaces
therecursionwithaniterationloop.Asanimprovementoveradirectimplemen
tationoftherecursion,wedynamicallymaintainthepermutationmatrixPasan
array,whereiDjmeansthattheithrowofPcontainsa1incolumnj.
WealsoimplementthecodetocomputeLandUinplaceinthematrixA.Thus,
whentheprocedureterminates,
(
lij ifi>j
aijD
uij ifij:
Figure28.2illustrateshowLUPDECOMPOSITIONfactorsamatrix.Lines34
initializethearray torepresenttheidentitypermutation.Theouterforloop
beginninginline5implementstherecursion.Eachtimethroughtheouterloop,
lines610determinetheelementak kwithlargestabsolutevalueofthoseinthe
0

currentfirstcolumn(columnk)ofthe.nkC1/.nkC1/matrixwhose
LUPdecompositionwearefinding.Ifallelementsinthecurrentfirstcolumnare
zero,lines1112reportthatthematrixissingular.Topivot,weexchangek0
withkinline13andexchangethekthandk0throwsofAinlines1415,
therebymakingthepivotelementakk.(Theentirerowsareswappedbecausein
thederivationofthemethodabove,notonlyisA0 wT=ak1multipliedbyP0,but
sois=ak1.)Finally,theSchurcomplementiscomputedbylines1619inmuch
thesamewayasitiscomputedbylines712ofLUDECOMPOSITION,exceptthat
heretheoperationiswrittentoworkinplace.
Becauseofitstriplynestedloopstructure,LUPDECOMPOSITIONhasarun
ningtimeof.n3/,whichisthesameasthatofLUDECOMPOSITION.Thus,
pivotingcostsusatmostaconstantfactorintime.

Exercises

28.11
Solvetheequation
100 x1 3
410 x2 re 14
651 x3 7
byusingforwardsubstitution.

28.12
FindanLUdecompositionofthematrix
4 5 6
8 6 7 :
12 712

https://translate.googleusercontent.com/translate_f 152/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Pgina247

826 Chapter28MatrixOperations

1 2 0 2 0.6 3 5 5 4 2 3 5 5 4 2
2 3 3 4 2 2 3 3 4 2 2 0.6 0 1.63.2
3 5 5 4 2 1 2 0 2 0.6 1 0.420.4.2
4 123.41 4 123.41 4 0.214.20.6
(un) (segundo) (do)

3 5 5 4 2 3 5 5 4 2 3 5 5 4 2
2 0.6 0 1.63.2 1 0.420.40.2 1 0.420.40.2
1 0.420.40.2 2 0.6 0 1.63.2 2 0.6 0 1.63.2
4 0.214.20.6 4 0.214.20.6 4 0.20.5 40.5
(re) (mi) (f)

3 5 5 4 2 3 5 5 4 2 3 5 5 4 2
1 0.420.40.2 1 0.420.40.2 1 0.420.40.2
2 0.6 0 1.63.2 4 0.20.5 40.5 4 0.20.5 40.5
4 0.20.5 40.5 2 0.6 0 1.63.2 2 0.6 0 0.43
(gramo) (marido) (yo)

0010 2 0 2 0:6 1 0 0 0 55 4 2
1000 3 3 4 2 re 0:4 1 0 0 0 20:4 0:2
0001 5 5 4 2 0:20:5 1 0 00 4 0:5
0100 1 23:4 1 0:6 0 0:41 00 0 3
PAG UN L Tu
(J)

Figure28.2TheoperationofLUPDECOMPOSITION.(a)TheinputmatrixAwiththeidentity
permutationoftherowsontheleft.Thefirststepofthealgorithmdeterminesthattheelement5
intheblackcircleinthethirdrowisthepivotforthefirstcolumn.(b)Rows1and3areswapped
andthepermutationisupdated.TheshadedcolumnandrowrepresentandwT.(c)Thevector
isreplacedby=5,andthelowerrightofthematrixisupdatedwiththeSchurcomplement.Lneas
dividethematrixintothreeregions:elementsofU(above),elementsofL(left),andelementsofthe
Schurcomplement(lowerright).(d)(f)Thesecondstep.(g)(i)Thethirdstep.Nofurtherchanges
occuronthefourth(final)step.(j)TheLUPdecompositionPADLU.

Pgina248

28.2Invertingmatrices 827

28.13
Solvetheequation
154 x1 12
203 x2 re 9
582 x3 5
byusinganLUPdecomposition.

28.14
DescribetheLUPdecompositionofadiagonalmatrix.

28.15
DescribetheLUPdecompositionofapermutationmatrixA,andprovethatitis
unique.

28.16
Showthatforalln 1,thereexistsasingularnnmatrixthathasanLUdecom
position.

28.17
InLUDECOMPOSITION,isitnecessarytoperformtheoutermostforloopitera
tionwhenkDn?HowaboutinLUPDECOMPOSITION?

28.2Invertingmatrices

https://translate.googleusercontent.com/translate_f 153/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Althoughinpracticewedonotgenerallyusematrixinversestosolvesystemsof
linearequations,preferringinsteadtousemorenumericallystabletechniquessuch
asLUPdecomposition,sometimesweneedtocomputeamatrixinverse.Enesto
section,weshowhowtouseLUPdecompositiontocomputeamatrixinverse.
Wealsoprovethatmatrixmultiplicationandcomputingtheinverseofamatrix
areequivalentlyhardproblems,inthat(subjecttotechnicalconditions)wecan
useanalgorithmforonetosolvetheotherinthesameasymptoticrunningtime.
Thus,wecanuseStrassen'salgorithm(seeSection4.2)formatrixmultiplication
toinvertamatrix.Indeed,Strassen'soriginalpaperwasmotivatedbytheproblem
ofshowingthatasetofalinearequationscouldbesolvedmorequicklythanby
theusualmethod.

Pgina249

828 Chapter28MatrixOperations

ComputingamatrixinversefromanLUPdecomposition
SupposethatwehaveanLUPdecompositionofamatrixAintheformofthree
matricesL,U,andPsuchthatPADLU.UsingLUPSOLVE,wecansolve
anequationoftheformAxDbintime.n2/.SincetheLUPdecomposition
dependsonAbutnotb,wecanrunLUPSOLVEonasecondsetofequationsof
theformAxDb0inadditionaltime.n2/.Ingeneral,oncewehavetheLUP
decompositionofA,wecansolve,intime.kn2/,kversionsoftheequation
AxDbthatdifferonlyinb.
Wecanthinkoftheequation
AXDIn (28.10)
whichdefinesthematrixX,theinverseofA,asasetofndistinctequationsofthe
formAxDb.Tobeprecise,letXidenotetheithcolumnofX,andrecallthatthe
unitvectoreiistheithcolumnofIn.Wecanthensolveequation(28.10)forXby
usingtheLUPdecompositionforAtosolveeachequation
AXiDei
separatelyforXi.OncewehavetheLUPdecomposition,wecancomputeeachof
thencolumnsXiintime.n2/,andsowecancomputeXfromtheLUPdecom
positionofAintime.n3/.SincewecandeterminetheLUPdecompositionofA
intime.n3/,wecancomputetheinverseA1ofamatrixAintime.n3/.

Matrixmultiplicationandmatrixinversion
Wenowshowthatthetheoreticalspeedupsobtainedformatrixmultiplication
translatetospeedupsformatrixinversion.Infact,weprovesomethingstronger:
matrixinversionisequivalenttomatrixmultiplication,inthefollowingsense.
IfMn/denotesthetimetomultiplytwon nmatrices,thenwecaninverta
nonsingularnnmatrixintimeOMn//.Moreover,ifIn/denotesthetime
toinvertanonsingularnnmatrix,thenwecanmultiplytwonnmatricesin
timeOIn//.Weprovetheseresultsastwoseparatetheorems.

Theorem28.1(Multiplicationisnoharderthaninversion)
Ifwecaninvertann nmatrixintimeIn/,whereIn/D .n2/andIn/
satisfiestheregularityconditionI.3n/DOIn//,thenwecanmultiplytwonn
matricesintimeOIn//.

ProofLetAandBbennmatriceswhosematrixproductCwewishtocom
pute.Wedefinethe3n3nmatrixDby

Pgina250

28.2Invertingmatrices 829

En A0
DD 0In segundo
:
00In
TheinverseofDis
En AAB

https://translate.googleusercontent.com/translate_f 154/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
D1D 0 E
0n Esegundo
n

andthuswecancomputetheproductABbytakingtheupperrightnnsubmatrix
ofD1.
WecanconstructmatrixDin.n2/time,whichisOIn//becauseweassume
thatIn/D.n2/,andwecaninvertDinOI3n//DOIn//time,bythe
regularityconditiononIn/.WethushaveMn/DOIn//.

NotethatIn/satisfiestheregularityconditionwheneverIn/D.nclgdn/
foranyconstantsc>0andd 0.
Theproofthatmatrixinversionisnoharderthanmatrixmultiplicationrelies
onsomepropertiesofsymmetricpositivedefinitematricesthatwewillprovein
Section28.3.

Theorem28.2(Inversionisnoharderthanmultiplication)
SupposewecanmultiplytwonnrealmatricesintimeMn/,whereMn/D
.n2/andMn/satisfiesthetworegularityconditionsMnCk/DOMn//for
anykintherange0knandMn=2/cM.n/forsomeconstantc<1=2.
Thenwecancomputetheinverseofanyrealnonsingularn nmatrixintime
OMn//.

ProofWeprovethetheoremhereforrealmatrices.Exercise28.26asksyouto
generalizetheproofformatriceswhoseentriesarecomplexnumbers.
Wecanassumethatnisanexactpowerof2,sincewehave
UN 1 UN UN
A0 A1 0
re
0Ik 0 Ik
foranyk>0.Thus,bychoosingksuchthatnCkisapowerof2,weenlarge
thematrixtoasizethatisthenextpowerof2andobtainthedesiredanswerA1
fromtheanswertotheenlargedproblem.ThefirstregularityconditiononMn/
ensuresthatthisenlargementdoesnotcausetherunningtimetoincreasebymore
thanaconstantfactor.
Forthemoment,letusassumethatthennmatrixAissymmetricandpositive
definite.WepartitioneachofAanditsinverseA1intofourn=2n=2submatri
ces:

Pgina251

830 Chapter28MatrixOperations
UN UN UN UN
BCT RT
ANUNCIO andA1D : (28,11)
discoscompactos UV
Then,ifwelet
SDDCB1CT (28,12)
betheSchurcomplementofAwithrespecttoB(weshallseemoreaboutthisform
ofSchurcomplementinSection28.3),wehave
UN UN UN UN
RT B1CB1CTS1CB1 B1CTS1
A1D re (28,13)
UV S1CB1 S1
sinceAA1DIn,asyoucanverifybyperformingthematrixmultiplication.Ser
causeAissymmetricandpositivedefinite,Lemmas28.4and28.5inSection28.3
implythatBandSarebothsymmetricandpositivedefinite.ByLemma28.3in
Section28.3,therefore,theinversesB1andS1exist,andbyExerciseD.26,
B1andS1aresymmetric,sothat.B1/TDB1and.S1/TDS1.Ah
fore,wecancomputethesubmatricesR,T,U,andVofA1asfollows,where
allmatricesmentionedaren=2n=2:
1.FormthesubmatricesB,C,CT,andDofA.
2.RecursivelycomputetheinverseB1ofB.
3.ComputethematrixproductWDCB1,andthencomputeitstransposeWT,
whichequalsB1CT(byExerciseD.12and.B1/TDB1).
4.ComputethematrixproductXDWCT,whichequalsCB1CT,andthen
computethematrixSDDXDDCB1CT.
5.RecursivelycomputetheinverseS1ofS,andsetVtoS1.
6.ComputethematrixproductYDS1W,whichequalsS1CB1,and
thencomputeitstransposeYT,whichequalsB1CTS1(byExerciseD.12,
.B1/TDB1,and.S1/TDS1).SetTtoYTandUtoY.
7.ComputethematrixproductZDWTY,whichequalsB1CTS1CB1,and
setRtoB1CZ.
Thus,wecaninvertannnsymmetricpositivedefinitematrixbyinvertingtwo
n=2n=2matricesinsteps2and5performingfourmultiplicationsofn=2n=2
matricesinsteps3,4,6,and7plusanadditionalcostofOn2/forextracting
submatricesfromA,insertingsubmatricesintoA1,andperformingaconstant
numberofadditions,subtractions,andtransposesonn=2n=2matrices.Obtenemos
therecurrence
https://translate.googleusercontent.com/translate_f 155/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

In/2I.n=2/C4M.n=2/COn2/
D2I.n=2/C.Mn//
DOMn//:

Pgina252

28.2Invertingmatrices 831

Thesecondlineholdsbecausethesecondregularityconditioninthestatement
ofthetheoremimpliesthat4M.n=2/<2M.n/andbecauseweassumethat
Mn/D.n2/.Thethirdlinefollowsbecausethesecondregularitycondition
allowsustoapplycase3ofthemastertheorem(Theorem4.1).
Itremainstoprovethatwecanobtainthesameasymptoticrunningtimeforma
trixmultiplicationasformatrixinversionwhenAisinvertiblebutnotsymmetric
andpositivedefinite.ThebasicideaisthatforanynonsingularmatrixA,thema
trixATAissymmetric(byExerciseD.12)andpositivedefinite(byTheoremD.6).
Thetrick,then,istoreducetheproblemofinvertingAtotheproblemofinvert
ingATA.
ThereductionisbasedontheobservationthatwhenAisannnnonsingular
matrix,wehave
A1D.ATA/1AT

since..ATA/1AT/AD.ATA/1.ATA/DInandamatrixinverseisunique.
Therefore,wecancomputeA1byfirstmultiplyingATbyAtoobtainATA,then
invertingthesymmetricpositivedefinitematrixATAusingtheabovedivideand
conqueralgorithm,andfinallymultiplyingtheresultbyAT.Eachofthesethree
stepstakesOMn//time,andthuswecaninvertanynonsingularmatrixwithreal
entriesinOMn//time.

TheproofofTheorem28.2suggestsameansofsolvingtheequationAxDb
byusingLUdecompositionwithoutpivoting,solongasAisnonsingular.Nosotros
multiplybothsidesoftheequationbyAT,yielding.ATA/xDATb.Thistrans
formationdoesn'taffectthesolutionx,sinceATisinvertible,andsowecanfac
torthesymmetricpositivedefinitematrixATAbycomputinganLUdecomposi
Cin.Wethenuseforwardandbacksubstitutiontosolveforxwiththerighthand
sideATb.Althoughthismethodistheoreticallycorrect,inpracticetheprocedure
LUPDECOMPOSITIONworksmuchbetter.LUPdecompositionrequiresfewer
arithmeticoperationsbyaconstantfactor,andithassomewhatbetternumerical
properties.

Exercises

28.21
LetMn/bethetimetomultiplytwonnmatrices,andletSn/denotethetime
requiredtosquareann nmatrix.Showthatmultiplyingandsquaringmatri
ceshaveessentiallythesamedifficulty:anMn/timematrixmultiplicational
gorithmimpliesanOMn//timesquaringalgorithm,andanSn/timesquaring
algorithmimpliesanOSn//timematrixmultiplicationalgorithm.

Pgina253

832 Chapter28MatrixOperations

28.22
LetMn/bethetimetomultiplytwonnmatrices,andletLn/bethetimeto
computetheLUPdecompositionofannnmatrix.Showthatmultiplyingmatri
cesandcomputingLUPdecompositionsofmatriceshaveessentiallythesamedif
ficulty:anMn/timematrixmultiplicationalgorithmimpliesanOMn//time
LUPdecompositionalgorithm,andanLn/timeLUPdecompositionalgorithm
impliesanOLn//timematrixmultiplicationalgorithm.

28.23
LetMn/bethetimetomultiplytwon nmatrices,andletDn/denotethe
timerequiredtofindthedeterminantofann nmatrix.Showthatmultiply
ingmatricesandcomputingthedeterminanthaveessentiallythesamedifficulty:
anMn/timematrixmultiplicationalgorithmimpliesanOMn//timedetermi
nantalgorithm,andaDn/timedeterminantalgorithmimpliesanODn//time
matrixmultiplicationalgorithm.

28.24
LetMn/bethetimetomultiplytwonnbooleanmatrices,andletT.n/bethe

https://translate.googleusercontent.com/translate_f 156/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
timetofindthetransitiveclosureofannnbooleanmatrix.(SeeSection25.2.)
ShowthatanMn/timebooleanmatrixmultiplicationalgorithmimpliesan
OMn/lgn/timetransitiveclosurealgorithm,andaT.n/timetransitiveclosure
algorithmimpliesanOT.n//timebooleanmatrixmultiplicationalgorithm.

28.25
DoesthematrixinversionalgorithmbasedonTheorem28.2workwhenmatrix
elementsaredrawnfromthefieldofintegersmodulo2?Explique.

28.26?
GeneralizethematrixinversionalgorithmofTheorem28.2tohandlematricesof
complexnumbers,andprovethatyourgeneralizationworkscorrectly.(Hint:In
steadofthetransposeofA,usetheconjugatetransposeA,whichyouobtainfrom
thetransposeofAbyreplacingeveryentrywithitscomplexconjugate.Enlugarde
symmetricmatrices,considerHermitianmatrices,whicharematricesAsuchthat
ADA.)

28.3Symmetricpositivedefinitematricesandleastsquaresapproximation

Symmetricpositivedefinitematriceshavemanyinterestinganddesirableproper
ties.Forexample,theyarenonsingular,andwecanperformLUdecomposition
onthemwithouthavingtoworryaboutdividingby0.Inthissection,weshall

Pgina254

28.3Symmetricpositivedefinitematricesandleastsquaresapproximation 833

proveseveralotherimportantpropertiesofsymmetricpositivedefinitematrices
andshowaninterestingapplicationtocurvefittingbyaleastsquaresapproxima
Cin.
Thefirstpropertyweproveisperhapsthemostbasic.

Lemma28.3
Anypositivedefinitematrixisnonsingular.

ProofSupposethatamatrixAissingular.ThenbyCorollaryD.3,thereexistsa
nonzerovectorxsuchthatAxD0.Hence,xTAxD0,andAcannotbepositive
definite.

TheproofthatwecanperformLUdecompositiononasymmetricpositive
definitematrixAwithoutdividingby0ismoreinvolved.Webeginbyproving
propertiesaboutcertainsubmatricesofA.DefinethekthleadingsubmatrixofA
tobethematrixAkconsistingoftheintersectionofthefirstkrowsandfirstk
columnsofA.

Lemma28.4
IfAisasymmetricpositivedefinitematrix,theneveryleadingsubmatrixofAis
symmetricandpositivedefinite.

ProofThateachleadingsubmatrixAkissymmetricisobvious.ToprovethatAk
ispositivedefinite,weassumethatitisnotandderiveacontradiction.IfAkisnot
positivedefinite,thenthereexistsakvectorxk0suchthatxT kAkxk0.LetA
benn,and
UN UN
Ak BT
ANUNCIO (28,14)
segundo
do
forsubmatricesB(whichis.nk/k)andC(whichis.nk/.nk/).Define
thenvectorxD.xT K 0/T,wherenk0sfollowxk.Thenwehave
UN UN
Ak BT xk
xTAxD.xT K 0/
segundodo 0
UN UN
Akxk
D.xT K 0/
Bxk
DxT kAkxk
0
whichcontradictsAbeingpositivedefinite.

Pgina255

834 Chapter28MatrixOperations
https://translate.googleusercontent.com/translate_f 157/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

WenowturntosomeessentialpropertiesoftheSchurcomplement.LetAbe
asymmetricpositivedefinitematrix,andletAkbealeadingk ksubmatrix
ofA.PartitionAonceagainaccordingtoequation(28.14).Wegeneralizeequa
tion(28.9)todefinetheSchurcomplementSofAwithrespecttoAkas
SDC BAk
1
BT: (28.15)
(ByLemma28.4,Akissymmetricandpositivedefinitetherefore,A1 existsby
K
Lemma28.3,andSiswelldefined.)Notethatourearlierdefinition(28.9)ofthe
Schurcomplementisconsistentwithequation(28.15),bylettingkD1.
ThenextlemmashowsthattheSchurcomplementmatricesofsymmetricposi
tivedefinitematricesarethemselvessymmetricandpositivedefinite.Weusedthis
resultinTheorem28.2,andweneeditscorollarytoprovethecorrectnessofLU
decompositionforsymmetricpositivedefinitematrices.

Lemma28.5(Schurcomplementlemma)
IfAisasymmetricpositivedefinitematrixandAkisaleadingkksubmatrix
ofA,thentheSchurcomplementSofAwithrespecttoAkissymmetricand
positivedefinite.

ProofBecauseAissymmetric,soisthesubmatrixC.ByExerciseD.26,the
productBA1
kBTissymmetric,andbyExerciseD.11,Sissymmetric.
ItremainstoshowthatSispositivedefinite.ConsiderthepartitionofAgivenin
equation(28.14).Foranynonzerovectorx,wehavexTAx>0bytheassumption
thatAispositivedefinite.Letusbreakxintotwosubvectorsyandcompatible
withAkandC,respectively.BecauseA1K exists,wehave
UN UN
Ak BT
xTAxD.yT T/
segundo
do
UN UN
AkyCBT
D.yT T/
ByCC
DyTAkyCyTBTCTByCTC
D.yCA1 kBT/TAk.yCA1 kBT/CT.C BAk
1
BT/
(28.16)
bymatrixmagic.(Verifybymultiplyingthrough.)Thislastequationamountsto
completingthesquareofthequadraticform.(SeeExercise28.32.)
SincexTAx>0holdsforanynonzerox,letuspickanynonzeroandthen
chooseyDA1
kBT,whichcausesthefirstterminequation(28.16)tovanish,
leaving
T.C BA1
kBT/DTS
asthevalueoftheexpression.Forany0,wethereforehaveTSD
xTAx>0,andthusSispositivedefinite.

Pgina256

28.3Symmetricpositivedefinitematricesandleastsquaresapproximation 835

Corollary28.6
LUdecompositionofasymmetricpositivedefinitematrixnevercausesadivision
by0.

ProofLetAbeasymmetricpositivedefinitematrix.Weshallprovesomething
strongerthanthestatementofthecorollary:everypivotisstrictlypositive.Elprimero
pivotisa11.Lete1bethefirstunitvector,fromwhichweobtaina11DeT1Ae1>0.
SincethefirststepofLUdecompositionproducestheSchurcomplementofA
withrespecttoA1D.a11/,Lemma28.5impliesbyinductionthatallpivotsare
positivo.

Leastsquaresapproximation
Oneimportantapplicationofsymmetricpositivedefinitematricesarisesinfitting
curvestogivensetsofdatapoints.Supposethatwearegivenasetofmdatapoints
.x1y1/.x2y2/:::.xmym/

whereweknowthattheyiaresubjecttomeasurementerrors.Wewouldliketo
determineafunctionFx/suchthattheapproximationerrors
iDF.xi/yi (28.17)
aresmallforiD12:::metro.TheformofthefunctionFdependsontheproblem
amano.Here,weassumethatithastheformofalinearlyweightedsum,
x norte
Fx/D cjfj.x/
jD1
wherethenumberofsummandsnandthespecificbasisfunctionsfjarechosen
basedonknowledgeoftheproblemathand.Acommonchoiceisfj.x/Dxj1,

https://translate.googleusercontent.com/translate_f 158/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
whichmeansthat
Fx/Dc1Cc2xCc3x2CCcnxn1
isapolynomialofdegreen1inx.Thus,givenmdatapoints.x1y1/.x2y2/
:::.xmym/,wewishtocalculatencoefficientsc1c2:::cnthatminimizethe
approximationerrors12:::m.
BychoosingnDm,wecancalculateeachyiexactlyinequation(28.17).Tal
ahighdegreeFfitsthenoiseaswellasthedata,however,andgenerallygives
poorresultswhenusedtopredictyforpreviouslyunseenvaluesofx.Itisusu
allybettertochoosensignificantlysmallerthanmandhopethatbychoosingthe
coefficientscjwell,wecanobtainafunctionFthatfindsthesignificantpatterns
inthedatapointswithoutpayingundueattentiontothenoise.Sometheoretical

Pgina257

836 Chapter28MatrixOperations

principlesexistforchoosingn,buttheyarebeyondthescopeofthistext.Encualquier
case,oncewechooseavalueofnthatislessthanm,weendupwithanoverde
terminedsetofequationswhosesolutionwewishtoapproximate.Wenowshow
howtodoso.

Dejar
f1.x1/f2.x1/:::fn.x1/
f1.x2/f2.x2/:::fn.x2/
ANUNCIO Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
f1.xm/f2.xm/:::fn.xm/
denotethematrixofvaluesofthebasisfunctionsatthegivenpointsesdecir,
aijDfj.xi/.LetcD.ck/denotethedesirednvectorofcoefficients.Entonces,

f1.x1/f2.x1/:::fn.x1/ c1
f1.x2/f2.x2/:::fn.x2/ c2
AcD Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
Unesdoc.unesco.orgunesdoc.unesco.org
f1.xm/f2.xm/:::fn.xm/ cn
F.x1/
F.x2/
re Unesdoc.unesco.orgunesdoc.unesco.org
F.xm/

isthemvectorofpredictedvaluesfory.As,
DAcy
isthemvectorofapproximationerrors.
Tominimizeapproximationerrors,wechoosetominimizethenormoftheerror
vector,whichgivesusaleastsquaressolution,since
!1=2
xmetro
kkD yo2 :
ID1
Porque
!2
xmetroxnorte
kk 2 DkAcyk 2 D aijcj yi
ID1 jD1
wecanminimizekkbydifferentiatingkk 2 withrespecttoeachckandthen
settingtheresultto0:

Pgina258

28.3Symmetricpositivedefinitematricesandleastsquaresapproximation 837
!
dkk2 xmetro xnorte
re 2 aijcj yi aikD0: (28.18)
dck
ID1 jD1
Thenequations(28.18)forkD12:::nareequivalenttothesinglematrix
ecuacin
.Acy/TAD0
or,equivalently(usingExerciseD.12),to
AT.Acy/D0
https://translate.googleusercontent.com/translate_f 159/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

whichimplies
ATAcDATy: (28.19)
Instatistics,thisiscalledthenormalequation.ThematrixATAissymmetric
byExerciseD.12,andifAhasfullcolumnrank,thenbyTheoremD.6,ATA
ispositivedefiniteaswell.Hence,.ATA/1exists,andthesolutiontoequa
tion(28.19)is
cD .ATA/1ATy
DACy (28.20)
wherethematrixACD..ATA/1AT/isthepseudoinverseofthematrixA.The
pseudoinversenaturallygeneralizesthenotionofamatrixinversetothecasein
whichAisnotsquare.(Compareequation(28.20)astheapproximatesolutionto
AcDywiththesolutionA1bastheexactsolutiontoAxDb.)
Asanexampleofproducingaleastsquaresfit,supposethatwehavefivedata
puntos
.x1y1/D.12/
.x2y2/D.11/
.x3y3/D.21/
.x4y4/D.30/
.x5y5/D.53/
shownasblackdotsinFigure28.3.Wewishtofitthesepointswithaquadratic
polynomial
Fx/Dc1Cc2xCc3x2:
Westartwiththematrixofbasisfunctionvalues

Pgina259

838 Chapter28MatrixOperations

Y
3,0

2,5

2,0 F(x)=1.20.757x+0.214x2

1,5

1.0

0,5

0,0 x
2 1 0 1 2 3 4 5

Figure28.3Theleastsquaresfitofaquadraticpolynomialtothesetoffivedatapoints
f.12/.11/.21/.30/.53/g.Theblackdotsarethedatapoints,andthewhitedotsaretheir
estimatedvaluespredictedbythepolynomialFx/D1:20:757xC0:214x2,thequadraticpoly
nomialthatminimizesthesumofthesquarederrors.Eachshadedlineshowstheerrorforonedata
punto.

1x1 x12 1 1 1
1x2 x22 1 1 1
ANUNCIO
1x3 x32 re 1 2 4
1x4 x42 1 3 9
1x5 x52 1 525
whosepseudoinverseis
0:500 0:300 0:200 0:100 0:100
ACD 0:388 0:093 0:190 0:193 0:088 :
0:060 0:036 0:048 0:036 0:060
MultiplyingybyAC,weobtainthecoefficientvector
1:200
cD 0:757
0:214

https://translate.googleusercontent.com/translate_f 160/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
whichcorrespondstothequadraticpolynomial

Pgina260

28.3Symmetricpositivedefinitematricesandleastsquaresapproximation 839

Fx/D1:2000:757xC0:214x2
astheclosestfittingquadratictothegivendata,inaleastsquaressense.
Asapracticalmatter,wesolvethenormalequation(28.19)bymultiplyingy
byATandthenfindinganLUdecompositionofATA.IfAhasfullrank,the
matrixATAisguaranteedtobenonsingular,becauseitissymmetricandpositive
definite.(SeeExerciseD.12andTheoremD.6.)

Exercises

28.31
Provethateverydiagonalelementofasymmetricpositivedefinitematrixisposi
Tivo.

28.32 UN UN
Ab
LetAD bea22symmetricpositivedefinitematrix.Provethatits
antesdeCristo
determinantacb2ispositivebycompletingthesquareinamannersimilarto
thatusedintheproofofLemma28.5.

28.33
Provethatthemaximumelementinasymmetricpositivedefinitematrixlieson
thediagonal.

28.34
Provethatthedeterminantofeachleadingsubmatrixofasymmetricpositive
definitematrixispositive.

28.35
LetAkdenotethekthleadingsubmatrixofasymmetricpositivedefinitematrixA.
Provethatdet.Ak/=det.Ak1/isthekthpivotduringLUdecomposition,where,
byconvention,det.A0/D1.

28.36
Findthefunctionoftheform
Fx/Dc1Cc2xlgxCc3ex
thatisthebestleastsquaresfittothedatapoints
.11/.21/.33/.48/:

Pgina261

840 Chapter28MatrixOperations

28.37
ShowthatthepseudoinverseACsatisfiesthefollowingfourequations:
AACADA
ACAAC DAC
.AAC/T DAAC
.ACA/T DACA:

Problemas

281Tridiagonalsystemsoflinearequations

Considerthetridiagonalmatrix
1 1 0 0 0
1 2 1 0 0
ANUNCIO0 1 2 1 0 :
0 0 1 2 1
0 0 0 1 2

https://translate.googleusercontent.com/translate_f 161/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
a.FindanLUdecompositionofA.
segundo.SolvetheequationAxD11111 T byusingforwardandbacksub
stitution.

do.FindtheinverseofA.

re.Showhow,foranynnsymmetricpositivedefinite,tridiagonalmatrixAand
anynvectorb,tosolvetheequationAxDbinOn/timebyperformingan
LUdecomposition.ArguethatanymethodbasedonformingA1isasymptot
icallymoreexpensiveintheworstcase.

mi.Showhow,foranynnnonsingular,tridiagonalmatrixAandanynvectorb,to
solvetheequationAxDbinOn/timebyperforminganLUPdecomposition.

282Splines
Apracticalmethodforinterpolatingasetofpointswithacurveistousecu
bicsplines.Wearegivenasetfxiyi/WiD01:::ngofnC1pointvalue
pairs,wherex0<x1< <xn.Wewishtofitapiecewisecubiccurve
(spline)f.x/tothepoints.Thatis,thecurvef.x/ismadeupofncubicpolyno
mialsfi.x/DaiCbixCcix2Cdix3foriD01:::n1,whereifxfallsin

Pgina262

ProblemsforChapter28 841

therangexixxiC1,thenthevalueofthecurveisgivenbyf.x/Dfi.xxi/.
Thepointsxiatwhichthecubicpolynomialsarepastedtogetherarecalledknots.
Forsimplicity,weshallassumethatxiDiforiD01:::norte.
Toensurecontinuityoff.x/,werequirethat
f.xi/ Dfi.0/Dyi
f.xiC1/Dfi.1/DyiC1
foriD01:::n1.Toensurethatf.x/issufficientlysmooth,wealsoinsist
thatthefirstderivativebecontinuousateachknot:
f0.xiC1/Df0 i.1/Df0iC1.0/
foriD01:::n2.
a.SupposethatforiD01:::n,wearegivennotonlythepointvaluepairs
fxiyi/gbutalsothefirstderivativesDiDf0.xi/ateachknot.Expresseach
coefficientai,bi,ci,anddiintermsofthevaluesyi,yiC1,Di,andDiC1.
(RememberthatxiDi.)Howquicklycanwecomputethe4ncoefficients
fromthepointvaluepairsandfirstderivatives?
Thequestionremainsofhowtochoosethefirstderivativesoff.x/attheknots.
Onemethodistorequirethesecondderivativestobecontinuousattheknots:
f00.xiC1/Df00i.1/Df00iC1.0/
foriD01:::norte 2.Atthefirstandlastknots,weassumethatf00.x0/D
f0
00
.0/D0andf00.xn/Df00n1.1/D0theseassumptionsmakef.x/anatural
cubicspline.
segundo.UsethecontinuityconstraintsonthesecondderivativetoshowthatforiD
12:::n1,

Di1C4DiCDiC1D3.yiC1 yi1/: (28,21)

do.Muestraesa
2D0CD1 D3.y1 y0/ (28.22)
Dn1C2Dn D3.yn yn1/: (28,23)

re.Rewriteequations(28.21)(28.23)asamatrixequationinvolvingthevector
DDhD0D1:::Dniofunknowns.Whatattributesdoesthematrixinyour
equationhave?

mi.ArguethatanaturalcubicsplinecaninterpolateasetofnC1pointvaluepairs
inOn/time(seeProblem281).

Pgina263

842 Chapter28MatrixOperations

f.ShowhowtodetermineanaturalcubicsplinethatinterpolatesasetofnC1
points.xiyi/satisfyingx0<x1< <xn,evenwhenxiisnotnecessarily
https://translate.googleusercontent.com/translate_f 162/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
equaltoi.Whatmatrixequationmustyourmethodsolve,andhowquickly
doesyouralgorithmrun?

Chapternotes

Manyexcellenttextsdescribenumericalandscientificcomputationinmuchgreater
detailthanwehaveroomforhere.Thefollowingareespeciallyreadable:George
andLiu[132],GolubandVanLoan[144],Press,Teukolsky,Vetterling,andFlan
nery[283,284],andStrang[323,324].
GolubandVanLoan[144]discussnumericalstability.Theyshowwhydet.A/
isnotnecessarilyagoodindicatorofthestabilityofamatrixA,proposinginstead
Pn
tousekAk1kA1k1,wherekAk1Dmax1in jD1jaijj.Theyalsoaddress
thequestionofhowtocomputethisvaluewithoutactuallycomputingA1.
Gaussianelimination,uponwhichtheLUandLUPdecompositionsarebased,
wasthefirstsystematicmethodforsolvinglinearsystemsofequations.Tambinfue
oneoftheearliestnumericalalgorithms.Althoughitwasknownearlier,itsdis
coveryiscommonlyattributedtoCFGauss(17771855).Inhisfamouspaper
[325],StrassenshowedthatannnmatrixcanbeinvertedinOnlg7/time.Wino
grad[358]originallyprovedthatmatrixmultiplicationisnoharderthanmatrix
inversion,andtheconverseisduetoAho,Hopcroft,andUllman[5].
Anotherimportantmatrixdecompositionisthesingularvaluedecomposition,
orSVD.TheSVDfactorsanmnmatrixAintoADQ1QT
2,whereisan
mnmatrixwithnonzerovaluesonlyonthediagonal,Q1ismmwithmutually
orthonormalcolumns,andQ2isnn,alsowithmutuallyorthonormalcolumns.
Twovectorsareorthonormaliftheirinnerproductis0andeachvectorhasanorm
of1.ThebooksbyStrang[323,324]andGolubandVanLoan[144]containgood
treatmentsoftheSVD.
Strang[324]hasanexcellentpresentationofsymmetricpositivedefinitematri
cesandoflinearalgebraingeneral.

Pgina264

29 LinearProgramming

Manyproblemstaketheformofmaximizingorminimizinganobjective,given
limitedresourcesandcompetingconstraints.Ifwecanspecifytheobjectiveas
alinearfunctionofcertainvariables,andifwecanspecifytheconstraintson
resourcesasequalitiesorinequalitiesonthosevariables,thenwehavealinear
programmingproblem.Linearprogramsariseinavarietyofpracticalapplica
Ciones.Webeginbystudyinganapplicationinelectoralpolitics.

Apoliticalproblem
Supposethatyouareapoliticiantryingtowinanelection.Yourdistricthasthree
differenttypesofareasurban,suburban,andrural.Theseareashave,respec
tively,100,000,200,000,and50,000registeredvoters.Althoughnotallthereg
isteredvotersactuallygotothepolls,youdecidethattogoverneffectively,you
wouldlikeatleasthalftheregisteredvotersineachofthethreeregionstovotefor
t.Youarehonorableandwouldneverconsidersupportingpoliciesinwhichyou
donotbelieve.Yourealize,however,thatcertainissuesmaybemoreeffectivein
winningvotesincertainplaces.Yourprimaryissuesarebuildingmoreroads,gun
control,farmsubsidies,andagasolinetaxdedicatedtoimprovedpublictransit.
Accordingtoyourcampaignstaff'sresearch,youcanestimatehowmanyvotes
youwinorlosefromeachpopulationsegmentbyspending$1,000onadvertising
oneachissue.ThisinformationappearsinthetableofFigure29.1.Inthistable,

https://translate.googleusercontent.com/translate_f 163/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
eachentryindicatesthenumberofthousandsofeitherurban,suburban,orrural
voterswhowouldbewonoverbyspending$1,000onadvertisinginsupportofa
particularissue.Negativeentriesdenotevotesthatwouldbelost.Yourtaskisto
figureouttheminimumamountofmoneythatyouneedtospendinordertowin
50,000urbanvotes,100,000suburbanvotes,and25,000ruralvotes.
Youcould,bytrialanderror,deviseastrategythatwinstherequirednumber
ofvotes,butthestrategyyoucomeupwithmightnotbetheleastexpensiveone.
Forexample,youcoulddevote$20,000ofadvertisingtobuildingroads,$0togun
control,$4,000tofarmsubsidies,and$9,000toagasolinetax.Inthiscase,you

Pgina265

844 Chapter29LinearProgramming

poltica urban suburban rural


buildroads 2 5 3
guncontrol 8 2 5
farmsubsidies 0 0 10
gasolinetax 10 0 2

Figure29.1Theeffectsofpoliciesonvoters.Eachentrydescribesthenumberofthousandsof
urban,suburban,orruralvoterswhocouldbewonoverbyspending$1,000onadvertisingsupport
ofapolicyonaparticularissue.Negativeentriesdenotevotesthatwouldbelost.

wouldwin20.2/C0.8/C4.0/C9.10/D50thousandurbanvotes,20.5/C0.2/C
4.0/C9.0/D100thousandsuburbanvotes,and20.3/C0.5/C4.10/C9.2/D
82thousandruralvotes.Youwouldwintheexactnumberofvotesdesiredinthe
urbanandsuburbanareasandmorethanenoughvotesintheruralarea.(Infact,
intheruralarea,youwouldreceivemorevotesthantherearevoters.)Inorderto
garnerthesevotes,youwouldhavepaidfor20C0C4C9D33thousanddollars
ofadvertising.
Naturally,youmaywonderwhetherthisstrategyisthebestpossible.Thatis,
couldyouachieveyourgoalswhilespendinglessonadvertising?Additionaltrial
anderrormighthelpyoutoanswerthisquestion,butwouldn'tyouratherhavea
systematicmethodforansweringsuchquestions?Inordertodevelopone,weshall
formulatethisquestionmathematically.Weintroduce4variables:
x1isthenumberofthousandsofdollarsspentonadvertisingonbuildingroads,
x2isthenumberofthousandsofdollarsspentonadvertisingonguncontrol,
x3isthenumberofthousandsofdollarsspentonadvertisingonfarmsubsidies,
y
x4isthenumberofthousandsofdollarsspentonadvertisingonagasolinetax.
Wecanwritetherequirementthatwewinatleast50,000urbanvotesas
2x1C8x2C0x3C10x4 50: (29.1)
Similarly,wecanwritetherequirementsthatwewinatleast100,000suburban
votesand25,000ruralvotesas
5x1C2x2C0x3C0x4 100 (29.2)
y
3x1 5x2C10x3 2x4 25: (29.3)
Anysettingofthevariablesx1x2x3x4thatsatisfiesinequalities(29.1)(29.3)
yieldsastrategythatwinsasufficientnumberofeachtypeofvote.Afindeque

Pgina266

Chapter29LinearProgramming 845

keepcostsassmallaspossible,youwouldliketominimizetheamountspenton
advertising.Thatis,youwanttominimizetheexpression
x1Cx2Cx3Cx4: (29.4)
Althoughnegativeadvertisingoftenoccursinpoliticalcampaigns,thereisnosuch
thingasnegativecostadvertising.Consequently,werequirethat
x1 0x2 0x3 0andx4 0: (29,5)
Combininginequalities(29.1)(29.3)and(29.5)withtheobjectiveofminimiz
ing(29.4),weobtainwhatisknownasalinearprogram.Weformatthisproblem
como
minimize x1 do x2 do x3 do x4 (29,6)
https://translate.googleusercontent.com/translate_f 164/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
sujetoa
2x1 C8x2 do 0x3 C10x4 50 (29.7)
5x1 C2x2 do 0x3 do 0x4 100 (29,8)
3x1 5x2 C10x3 2x4 25 (29,9)
x1x2x3x4 0: (29.10)

Thesolutionofthislinearprogramyieldsyouroptimalstrategy.

Generallinearprograms
Inthegenerallinearprogrammingproblem,wewishtooptimizealinearfunction
subjecttoasetoflinearinequalities.Givenasetofrealnumbersa1a2:::anand
asetofvariablesx1x2:::xn,wedefinealinearfunctionfonthosevariables
por
xnorte
f.x1x2:::xn/Da1x1Ca2x2CCanxnD ajxj:
jD1
Ifbisarealnumberandfisalinearfunction,thentheequation
f.x1x2:::xn/Db
isalinearequalityandtheinequalities
f.x1x2:::xn/b

y
f.x1x2:::xn/ segundo

Pgina267

846 Chapter29LinearProgramming

arelinearinequalities.Weusethegeneraltermlinearconstraintstodenoteeither
linearequalitiesorlinearinequalities.Inlinearprogramming,wedonotallow
strictinequalities.Formally,alinearprogrammingproblemistheproblemof
eitherminimizingormaximizingalinearfunctionsubjecttoafinitesetoflinear
Restricciones.Ifwearetominimize,thenwecallthelinearprogramaminimization
linearprogram,andifwearetomaximize,thenwecallthelinearprograma
maximizationlinearprogram.
Theremainderofthischaptercovershowtoformulateandsolvelinearpro
GramosAlthoughseveralpolynomialtimealgorithmsforlinearprogramminghave
beendeveloped,wewillnotstudytheminthischapter.Instead,weshallstudythe
simplexalgorithm,whichistheoldestlinearprogrammingalgorithm.Thesimplex
algorithmdoesnotruninpolynomialtimeintheworstcase,butitisfairlyefficient
andwidelyusedinpractice.

Anoverviewoflinearprogramming
Inordertodescribepropertiesofandalgorithmsforlinearprograms,wefindit
convenienttoexpressthemincanonicalforms.Weshallusetwoforms,standard
andslack,inthischapter.WewilldefinethempreciselyinSection29.1.Infor
mally,alinearprograminstandardformisthemaximizationofalinearfunction
subjecttolinearinequalities,whereasalinearprograminslackformisthemax
imizationofalinearfunctionsubjecttolinearequalities.Weshalltypicallyuse
standardformforexpressinglinearprograms,butwefinditmoreconvenientto
useslackformwhenwedescribethedetailsofthesimplexalgorithm.Fornow,we
restrictourattentiontomaximizingalinearfunctiononnvariablessubjecttoaset
ofmlinearinequalities.
Letusfirstconsiderthefollowinglinearprogramwithtwovariables:
maximize x1 do x2 (29.11)
sujetoa
4x1 x2 UN 8 (29.12)
2x1 do x2 10 (29.13)
5x1 2x2 2 (29.14)
x1x2 0: (29.15)
Wecallanysettingofthevariablesx1andx2thatsatisfiesalltheconstraints
(29.12)(29.15)afeasiblesolutiontothelinearprogram.Ifwegraphthecon
straintsinthe.x1x2/Cartesiancoordinatesystem,asinFigure29.2(a),wesee

https://translate.googleusercontent.com/translate_f 165/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina268

Chapter29LinearProgramming 847

x2 x2
2
x2
2 8
5x1
x2
4x1 x
1+x
0
2=8
x1 2x
1+x x
1+x
2 2=4
10
x
x1 1+x x1
x2 0 2=0
(un) (segundo)

Figure29.2(a)Thelinearprogramgivenin(29.12)(29.15).Eachconstraintisrepresentedby
alineandadirection.Theintersectionoftheconstraints,whichisthefeasibleregion,isshaded.
(b)Thedottedlinesshow,respectively,thepointsforwhichtheobjectivevalueis0,4,and8.The
optimalsolutiontothelinearprogramisx1D2andx2D6withobjectivevalue8.

thatthesetoffeasiblesolutions(shadedinthefigure)formsaconvexregion1in
thetwodimensionalspace.Wecallthisconvexregionthefeasibleregionandthe
functionwewishtomaximizetheobjectivefunction.Conceptually,wecouldeval
uatetheobjectivefunctionx1Cx2ateachpointinthefeasibleregionwecallthe
valueoftheobjectivefunctionataparticularpointtheobjectivevalue.Wecould
thenidentifyapointthathasthemaximumobjectivevalueasanoptimalsolution.
Forthisexample(andformostlinearprograms),thefeasibleregioncontainsan
infinitenumberofpoints,andsoweneedtodetermineanefficientwaytofinda
pointthatachievesthemaximumobjectivevaluewithoutexplicitlyevaluatingthe
objectivefunctionateverypointinthefeasibleregion.
Intwodimensions,wecanoptimizeviaagraphicalprocedure.Thesetofpoints
forwhichx1Cx2D,forany,isalinewithaslopeof1.Ifweplotx1Cx2D0,
weobtainthelinewithslope1throughtheorigin,asinFigure29.2(b).los
intersectionofthislineandthefeasibleregionisthesetoffeasiblesolutionsthat
haveanobjectivevalueof0.Inthiscase,thatintersectionofthelinewiththe
feasibleregionisthesinglepoint.00/.Moregenerally,forany,theintersection

1Anintuitivedefinitionofaconvexregionisthatitfulfillstherequirementthatforanytwopointsin
theregion,allpointsonalinesegmentbetweenthemarealsointheregion.

Pgina269

848 Chapter29LinearProgramming

ofthelinex1Cx2Dandthefeasibleregionisthesetoffeasiblesolutionsthat
haveobjectivevalue.Figure29.2(b)showsthelinesx1Cx2D0,x1Cx2D4,
andx1Cx2D8.BecausethefeasibleregioninFigure29.2isbounded,there
mustbesomemaximumvalueforwhichtheintersectionofthelinex1Cx2D
andthefeasibleregionisnonempty.Anypointatwhichthisoccursisanoptimal
solutiontothelinearprogram,whichinthiscaseisthepointx1D2andx2D6
withobjectivevalue8.
Itisnoaccidentthatanoptimalsolutiontothelinearprogramoccursatavertex
ofthefeasibleregion.Themaximumvalueofforwhichthelinex1Cx2D
intersectsthefeasibleregionmustbeontheboundaryofthefeasibleregion,and
thustheintersectionofthislinewiththeboundaryofthefeasibleregioniseithera
singlevertexoralinesegment.Iftheintersectionisasinglevertex,thenthereis
justoneoptimalsolution,anditisthatvertex.Iftheintersectionisalinesegment,
everypointonthatlinesegmentmusthavethesameobjectivevalueinparticular,
bothendpointsofthelinesegmentareoptimalsolutions.Sinceeachendpointofa
linesegmentisavertex,thereisanoptimalsolutionatavertexinthiscaseaswell.
Althoughwecannoteasilygraphlinearprogramswithmorethantwovariables,
thesameintuitionholds.Ifwehavethreevariables,theneachconstraintcorre
spondstoahalfspaceinthreedimensionalspace.Theintersectionofthesehalf
spacesformsthefeasibleregion.Thesetofpointsforwhichtheobjectivefunction
obtainsagivenvalueisnowaplane(assumingnodegenerateconditions).Mecaigo
coefficientsoftheobjectivefunctionarenonnegative,andiftheoriginisafeasible
solutiontothelinearprogram,thenaswemovethisplaneawayfromtheorigin,in
adirectionnormaltotheobjectivefunction,wefindpointsofincreasingobjective

https://translate.googleusercontent.com/translate_f 166/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
valor.(Iftheoriginisnotfeasibleorifsomecoefficientsintheobjectivefunction
arenegative,theintuitivepicturebecomesslightlymorecomplicated.)Asintwo
dimensions,becausethefeasibleregionisconvex,thesetofpointsthatachieve
theoptimalobjectivevaluemustincludeavertexofthefeasibleregion.Simi
larly,ifwehavenvariables,eachconstraintdefinesahalfspaceinndimensional
espacio.Wecallthefeasibleregionformedbytheintersectionofthesehalfspacesa
simplex.Theobjectivefunctionisnowahyperplaneand,becauseofconvexity,an
optimalsolutionstilloccursatavertexofthesimplex.
Thesimplexalgorithmtakesasinputalinearprogramandreturnsanoptimal
solucin.Itstartsatsomevertexofthesimplexandperformsasequenceofitera
Ciones.Ineachiteration,itmovesalonganedgeofthesimplexfromacurrentvertex
toaneighboringvertexwhoseobjectivevalueisnosmallerthanthatofthecurrent
vertex(andusuallyislarger.)Thesimplexalgorithmterminateswhenitreaches
alocalmaximum,whichisavertexfromwhichallneighboringverticeshavea
smallerobjectivevalue.Becausethefeasibleregionisconvexandtheobjective
functionislinear,thislocaloptimumisactuallyaglobaloptimum.InSection29.4,

Pgina270

Chapter29LinearProgramming 849

weshalluseaconceptcalleddualitytoshowthatthesolutionreturnedbythe
simplexalgorithmisindeedoptimal.
Althoughthegeometricviewgivesagoodintuitiveviewoftheoperationsofthe
simplexalgorithm,weshallnotrefertoitexplicitlywhendevelopingthedetails
ofthesimplexalgorithminSection29.3.Instead,wetakeanalgebraicview.Nosotros
firstwritethegivenlinearprograminslackform,whichisasetoflinearequalities.
Theselinearequalitiesexpresssomeofthevariables,calledbasicvariables,in
termsofothervariables,callednonbasicvariables.Wemovefromonevertex
toanotherbymakingabasicvariablebecomenonbasicandmakinganonbasic
variablebecomebasic.Wecallthisoperationapivotand,viewedalgebraically,
itisnothingmorethanrewritingthelinearprograminanequivalentslackform.
Thetwovariableexampledescribedabovewasparticularlysimple.Weshall
needtoaddressseveralmoredetailsinthischapter.Theseissuesincludeiden
tifyinglinearprogramsthathavenosolutions,linearprogramsthathavenofinite
optimalsolution,andlinearprogramsforwhichtheoriginisnotafeasiblesolution.

Applicationsoflinearprogramming
Linearprogramminghasalargenumberofapplications.Anytextbookonopera
tionsresearchisfilledwithexamplesoflinearprogramming,andlinearprogram
minghasbecomeastandardtooltaughttostudentsinmostbusinessschools.los
electionscenarioisonetypicalexample.Twomoreexamplesoflinearprogram
mingarethefollowing:
Anairlinewishestoscheduleitsflightcrews.TheFederalAviationAdminis
trationimposesmanyconstraints,suchaslimitingthenumberofconsecutive
hoursthateachcrewmembercanworkandinsistingthataparticularcrewwork
onlyononemodelofaircraftduringeachmonth.Theairlinewantstoschedule
crewsonallofitsflightsusingasfewcrewmembersaspossible.
Anoilcompanywantstodecidewheretodrillforoil.Sitingadrillataparticu
larlocationhasanassociatedcostand,basedongeologicalsurveys,anexpected
payoffofsomenumberofbarrelsofoil.Thecompanyhasalimitedbudgetfor
locatingnewdrillsandwantstomaximizetheamountofoilitexpectstofind,
giventhisbudget.
Withlinearprograms,wealsomodelandsolvegraphandcombinatorialprob
lems,suchasthoseappearinginthistextbook.Wehavealreadyseenaspecial
caseoflinearprogrammingusedtosolvesystemsofdifferenceconstraintsinSec
tion24.4.InSection29.2,weshallstudyhowtoformulateseveralgraphand
networkflowproblemsaslinearprograms.InSection35.4,weshalluselinear
programmingasatooltofindanapproximatesolutiontoanothergraphproblem.

Pgina271

850 Chapter29LinearProgramming

Algorithmsforlinearprogramming
Thischapterstudiesthesimplexalgorithm.Thisalgorithm,whenimplemented
carefully,oftensolvesgenerallinearprogramsquicklyinpractice.Withsome
carefullycontrivedinputs,however,thesimplexalgorithmcanrequireexponential

https://translate.googleusercontent.com/translate_f 167/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
hora.Thefirstpolynomialtimealgorithmforlinearprogrammingwastheellipsoid
algorithm,whichrunsslowlyinpractice.Asecondclassofpolynomialtimealgo
rithmsareknownasinteriorpointmethods.Incontrasttothesimplexalgorithm,
whichmovesalongtheexteriorofthefeasibleregionandmaintainsafeasiblesolu
tionthatisavertexofthesimplexateachiteration,thesealgorithmsmovethrough
theinteriorofthefeasibleregion.Theintermediatesolutions,whilefeasible,are
notnecessarilyverticesofthesimplex,butthefinalsolutionisavertex.Forlarge
inputs,interiorpointalgorithmscanrunasfastas,andsometimesfasterthan,the
simplexalgorithm.Thechapternotespointyoutomoreinformationaboutthese
Algoritmos
Ifweaddtoalinearprogramtheadditionalrequirementthatallvariablestake
onintegervalues,wehaveanintegerlinearprogram.Exercise34.53asksyou
toshowthatjustfindingafeasiblesolutiontothisproblemisNPhardyaque
nopolynomialtimealgorithmsareknownforanyNPhardproblems,thereisno
knownpolynomialtimealgorithmforintegerlinearprogramming.Incontrast,we
cansolveagenerallinearprogrammingprobleminpolynomialtime.
Inthischapter,ifwehavealinearprogramwithvariablesxD.x1x2:::xn/
andwishtorefertoaparticularsettingofthevariables,weshallusethenotation
NxD.Nx1Nx2:::Nxn/.

29.1Standardandslackforms

Thissectiondescribestwoformats,standardformandslackform,thatareuse
fulwhenwespecifyandworkwithlinearprograms.Instandardform,allthe
constraintsareinequalities,whereasinslackform,allconstraintsareequalities
(exceptforthosethatrequirethevariablestobenonnegative).

Standardform
Instandardform,wearegivennrealnumbersc1c2:::cnmrealnumbers
b1b2:::bmandmnrealnumbersaijforiD12:::mandjD12:::norte.
Wewishtofindnrealnumbersx1x2:::xnthat

Pgina272

29.1Standardandslackforms 851

xnorte
maximize cjxj (29.16)
jD1
sujetoa
xnorte
aijxj bi foriD12:::metro (29.17)
jD1
xj 0forjD12:::n: (29.18)

Generalizingtheterminologyweintroducedforthetwovariablelinearprogram,
wecallexpression(29.16)theobjectivefunctionandthenCminequalitiesin
lines(29.17)and(29.18)theconstraints.Thenconstraintsinline(29.18)arethe
nonnegativityconstraints.Anarbitrarylinearprogramneednothavenonnegativ
ityconstraints,butstandardformrequiresthem.Sometimeswefinditconvenient
toexpressalinearprograminamorecompactform.Ifwecreateanmnmatrix
AD.aij/,anmvectorbD.bi/,annvectorcD.cj/,andannvectorxD.xj/,
thenwecanrewritethelinearprogramdefinedin(29.16)(29.18)as
maximizecTx (29.19)
sujetoa
Axb (29.20)
x 0: (29.21)
Inline(29.19),cTxistheinnerproductoftwovectors.Ininequality(29.20),Ax
isamatrixvectorproduct,andininequality(29.21),x 0meansthateachentry
ofthevectorxmustbenonnegative.Weseethatwecanspecifyalinearprogram
instandardformbyatuple.Asegundoc/,andweshalladopttheconventionthatA,b,
andcalwayshavethedimensionsgivenabove.
Wenowintroduceterminologytodescribesolutionstolinearprograms.Weused
someofthisterminologyintheearlierexampleofatwovariablelinearprogram.
WecallasettingofthevariablesNxthatsatisfiesalltheconstraintsafeasiblesolu
tion,whereasasettingofthevariablesNxthatfailstosatisfyatleastoneconstraint
isaninfeasiblesolution.WesaythatasolutionNxhasobjectivevaluecTNx.Afea
siblesolutionNxwhoseobjectivevalueismaximumoverallfeasiblesolutionsisan
optimalsolution,andwecallitsobjectivevaluecTNxtheoptimalobjectivevalue.
Ifalinearprogramhasnofeasiblesolutions,wesaythatthelinearprogramisin
feasibleotherwiseitisfeasible.Ifalinearprogramhassomefeasiblesolutions

https://translate.googleusercontent.com/translate_f 168/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
butdoesnothaveafiniteoptimalobjectivevalue,wesaythatthelinearprogram
isunbounded.Exercise29.19asksyoutoshowthatalinearprogramcanhavea
finiteoptimalobjectivevalueevenifthefeasibleregionisnotbounded.

Pgina273

852 Chapter29LinearProgramming

Convertinglinearprogramsintostandardform
Itisalwayspossibletoconvertalinearprogram,givenasminimizingormaxi
mizingalinearfunctionsubjecttolinearconstraints,intostandardform.Alinear
programmightnotbeinstandardformforanyoffourpossiblereasons:
1.Theobjectivefunctionmightbeaminimizationratherthanamaximization.
2.Theremightbevariableswithoutnonnegativityconstraints.
3.Theremightbeequalityconstraints,whichhaveanequalsignratherthana
lessthanorequaltosign.
4.Theremightbeinequalityconstraints,butinsteadofhavingalessthanor
equaltosign,theyhaveagreaterthanorequaltosign.
WhenconvertingonelinearprogramLintoanotherlinearprogramL0,wewould
likethepropertythatanoptimalsolutiontoL0yieldsanoptimalsolutiontoL.To
capturethisidea,wesaythattwomaximizationlinearprogramsLandL0are
equivalentifforeachfeasiblesolutionNxtoLwithobjectivevalue,thereis
acorrespondingfeasiblesolutionNx0toL0withobjectivevalue,andforeach
feasiblesolutionNx0toL0withobjectivevalue,thereisacorrespondingfeasible
solutionNxtoLwithobjectivevalue.(Thisdefinitiondoesnotimplyaoneto
onecorrespondencebetweenfeasiblesolutions.)AminimizationlinearprogramL
andamaximizationlinearprogramL0areequivalentifforeachfeasiblesolutionNx
toLwithobjectivevalue,thereisacorrespondingfeasiblesolutionNx0toL0with
objectivevalue,andforeachfeasiblesolutionNx0toL0withobjectivevalue,
thereisacorrespondingfeasiblesolutionNxtoLwithobjectivevalue.
Wenowshowhowtoremove,onebyone,eachofthepossibleproblemsinthe
listabove.Afterremovingeachone,weshallarguethatthenewlinearprogramis
equivalenttotheoldone.
ToconvertaminimizationlinearprogramLintoanequivalentmaximizationlin
earprogramL0,wesimplynegatethecoefficientsintheobjectivefunction.Desde
LandL0haveidenticalsetsoffeasiblesolutionsand,foranyfeasiblesolution,the
objectivevalueinListhenegativeoftheobjectivevalueinL0,thesetwolinear
programsareequivalent.Forexample,ifwehavethelinearprogram
minimize 2x1 C3x2
sujetoa
x1 do x2 D7
x1 2x2 4
x1 0
andwenegatethecoefficientsoftheobjectivefunction,weobtain

Pgina274

29.1Standardandslackforms 853

maximize2x1 3x2
sujetoa
x1 do x2 D7
x1 2x2 4
x1 0:
Next,weshowhowtoconvertalinearprograminwhichsomeofthevariables
donothavenonnegativityconstraintsintooneinwhicheachvariablehasanon
negativityconstraint.Supposethatsomevariablexjdoesnothaveanonnegativity
constraint.Then,wereplaceeachoccurrenceofxjbyx0 J xj00,andaddthenon
negativityconstraintsx0 0andx00 0.Thus,iftheobjectivefunctionhasa
J J
termcjxj,wereplaceitbycjx0 cjx00
J j,andifconstraintihasatermaijxj,we
replaceitbyaijxJ0 aijxj.00Anyfeasiblesolutionyxtothenewlinearprogramcor
respondstoafeasiblesolutionNxtotheoriginallinearprogramwithNxjDyx J 0 yx
J 00
andwiththesameobjectivevalue.Also,anyfeasiblesolutionNxtotheoriginal
linearprogramcorrespondstoafeasiblesolutionyxtothenewlinearprogramwith

https://translate.googleusercontent.com/translate_f 169/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
yx
jDNx
0 jandyxj00
D0ifNxj 0,orwithyxj00DNxjandyx0
jD0ifNxj<0.Thetwo
linearprogramshavethesameobjectivevalueregardlessofthesignofNxj.Thus,
thetwolinearprogramsareequivalent.Weapplythisconversionschemetoeach
variablethatdoesnothaveanonnegativityconstrainttoyieldanequivalentlinear
programinwhichallvariableshavenonnegativityconstraints.
Continuingtheexample,wewanttoensurethateachvariablehasacorrespond
ingnonnegativityconstraint.Variablex1hassuchaconstraint,butvariablex2does
no.Therefore,wereplacex2bytwovariablesx02andx00 2,andwemodifythelinear
programtoobtain
maximize2x1 3x20 C3x00 2
sujetoa
x1 do x0 x00 D7 (29.22)
2 2
x1 2x20 C2x00 2 4
x1x0 0:
2x00
2
Next,weconvertequalityconstraintsintoinequalityconstraints.Supposethata
linearprogramhasanequalityconstraintf.x1x2:::xn/Db.SincexDyif
andonlyifbothx yandxy,wecanreplacethisequalityconstraintbythe
pairofinequalityconstraintsf.x1x2:::xn/bandf.x1x2:::xn/ segundo.
Repeatingthisconversionforeachequalityconstraintyieldsalinearprogramin
whichallconstraintsareinequalities.
Finally,wecanconvertthegreaterthanorequaltoconstraintstolessthanor
equaltoconstraintsbymultiplyingtheseconstraintsthroughby1.Thatis,any
inequalityoftheform

Pgina275

854 Chapter29LinearProgramming

xnorte
aijxj bi
jD1
esequivalentea
xnorte
aijxjbi:
jD1
Thus,byreplacingeachcoefficientaijbyaijandeachvaluebibybi,weobtain
anequivalentlessthanorequaltoconstraint.
Finishingourexample,wereplacetheequalityinconstraint(29.22)bytwoin
equalities,obtaining
maximize2x1 3x20 C3x00 2
sujetoa
x1 do x0 x00 7
2 2
x1 do x20 x200 7 (29.23)
x1 2x0 C2x00 4
2 2
x1x20 x00
2 0:
Finally,wenegateconstraint(29.23).Forconsistencyinvariablenames,were
namex0
2tox2andx00
2tox3,obtainingthestandardform
maximize 2x1 3x2 C3x3 (29.24)
sujetoa
x1 do x2 x3 UN 7 (29.25)
x1 x2 do x3 7 (29.26)
x1 2x2 C2x3 UN 4 (29.27)
x1x2x3 0: (29.28)

Convertinglinearprogramsintoslackform
Toefficientlysolvealinearprogramwiththesimplexalgorithm,weprefertoex
pressitinaforminwhichsomeoftheconstraintsareequalityconstraints.Ms
precisely,weshallconvertitintoaforminwhichthenonnegativityconstraintsare
theonlyinequalityconstraints,andtheremainingconstraintsareequalities.Dejar
xnorte
aijxjbi (29.29)
jD1

Pgina276

https://translate.googleusercontent.com/translate_f 170/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

29.1Standardandslackforms 855

beaninequalityconstraint.Weintroduceanewvariablesandrewriteinequal
ity(29.29)asthetwoconstraints
xnorte
sDbi aijxj (29.30)
jD1
S 0: (29.31)
Wecallsaslackvariablebecauseitmeasurestheslack,ordifference,between
thelefthandandrighthandsidesofequation(29.29).(Weshallsoonseewhywe
finditconvenienttowritetheconstraintwithonlytheslackvariableontheleft
handside.)Becauseinequality(29.29)istrueifandonlyifbothequation(29.30)
andinequality(29.31)aretrue,wecanconverteachinequalityconstraintofalin
earprograminthiswaytoobtainanequivalentlinearprograminwhichtheonly
inequalityconstraintsarethenonnegativityconstraints.Whenconvertingfrom
standardtoslackform,weshallusexnCi(insteadofs)todenotetheslackvariable
associatedwiththeithinequality.Theithconstraintistherefore
xnorte
xnCiDbi aijxj (29.32)
jD1
alongwiththenonnegativityconstraintxnCi 0.
Byconvertingeachconstraintofalinearprograminstandardform,weobtaina
linearprograminadifferentform.Forexample,forthelinearprogramdescribed
in(29.24)(29.28),weintroduceslackvariablesx4,x5,andx6,obtaining
maximize 2x1 3x2 C3x3 (29.33)
sujetoa
x4 re 7 x1 x2 do x3 (29.34)
x5 D7C x1 do x2 x3 (29.35)
x6 re 4 x1 C2x2 2x3 (29.36)
x1x2x3x4x5x6 0: (29.37)
Inthislinearprogram,alltheconstraintsexceptforthenonnegativityconstraints
areequalities,andeachvariableissubjecttoanonnegativityconstraint.Wewrite
eachequalityconstraintwithoneofthevariablesonthelefthandsideoftheequal
ityandallothersontherighthandside.Furthermore,eachequationhasthesame
setofvariablesontherighthandside,andthesevariablesarealsotheonlyones
thatappearintheobjectivefunction.Wecallthevariablesonthelefthandsideof
theequalitiesbasicvariablesandthoseontherighthandsidenonbasicvariables.
Forlinearprogramsthatsatisfytheseconditions,weshallsometimesomitthe
wordsmaximizeandsubjectto,aswellastheexplicitnonnegativitycon
StraintsWeshallalsousethevariabletodenotethevalueoftheobjectivefunc

Pgina277

856 Chapter29LinearProgramming

Cin.Wecalltheresultingformatslackform.Ifwewritethelinearprogramgiven
in(29.33)(29.37)inslackform,weobtain
D 2x1 3x2 C3x3 (29.38)
x4 re 7 x1 x2 do x3 (29.39)
x5 D7C x1 do x2 x3 (29.40)
x6 re 4 x1 C2x2 2x3: (29.41)
Aswithstandardform,wefinditconvenienttohaveamoreconcisenotation
fordescribingaslackform.AsweshallseeinSection29.3,thesetsofbasicand
nonbasicvariableswillchangeasthesimplexalgorithmruns.WeuseNtodenote
thesetofindicesofthenonbasicvariablesandBtodenotethesetofindicesof
thebasicvariables.WealwayshavethatjNjDn,jBjDm,andN[BD
f12:::nCmg.TheequationsareindexedbytheentriesofB,andthevariables
ontherighthandsidesareindexedbytheentriesofN.Asinstandardform,weuse
bi,cj,andaijtodenoteconstanttermsandcoefficients.Wealsousetodenote
anoptionalconstanttermintheobjectivefunction.(Weshallseealittlelaterthat
includingtheconstanttermintheobjectivefunctionmakesiteasytodeterminethe
valueoftheobjectivefunction.)Thuswecanconciselydefineaslackformbya
tuple.NBAsegundoc/,denotingtheslackform
x
D do cjxj (29.42)
xj2N
xi Dbi aijxj fori2B (29.43)
j2N
inwhichallvariablesxareconstrainedtobenonnegative.Becausewesubtract
PAG
thesum j2Naijxjin(29.43),thevaluesaijareactuallythenegativesofthe
https://translate.googleusercontent.com/translate_f 171/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
coefficientsastheyappearintheslackform.
Forexample,intheslackform
x3 x5 2x6
D28
6 6 3
x3 x5 x6
x1 re 8C do
6 6 3
8x3 2x5 x6
x2 re 4 do
3 3 3
x3 x5
x4 D18 do
2 2
wehaveBDf124g,NDf356g,

Pgina278

29.1Standardandslackforms 857

a13 a15 a16 1=6 1=61=3


ANUNCIO
a23 a25 a26 re 8=3 2=3 1=3
a43 a45 a46 1=2 1=2 0

b1 8
bD b2 re 4
b4 18

cDc3 c5 c6 T re 1=6 1=6 2=3 T,Y D28.Notethatthe


indicesintoA,b,andcarenotnecessarilysetsofcontiguousintegerstheydepend
ontheindexsetsBandN.AsanexampleoftheentriesofAbeingthenegatives
ofthecoefficientsastheyappearintheslackform,observethattheequationforx1
includesthetermx3=6,yetthecoefficienta13isactually1=6ratherthanC1=6.

Exercises

29.11
Ifweexpressthelinearprogramin(29.24)(29.28)inthecompactnotationof
(29.19)(29.21),whataren,m,A,b,andc?

29.12
Givethreefeasiblesolutionstothelinearprogramin(29.24)(29.28).Culesel
objectivevalueofeachone?

29.13
Fortheslackformin(29.38)(29.41),whatareN,B,A,b,c,and?

29.14
Convertthefollowinglinearprogramintostandardform:
minimize2x1 C7x2 Cx3
sujetoa
x1 x3 re 7
3x1 do x2 24
x2 0
x3 UN 0:

Page279

858 Chapter29LinearProgramming

29.15
Convertthefollowinglinearprogramintoslackform:
maximize 2x1 6x3
sujetoa
x1 do x2 x3 7
3x1 x2 8
x1 C2x2 C2x3 0

https://translate.googleusercontent.com/translate_f 172/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
x1x2x3 0:
Whatarethebasicandnonbasicvariables?

29.16
Showthatthefollowinglinearprogramisinfeasible:
maximize 3x1 2x2
sujetoa
x1 do x2 UN 2
2x1 2x2 10
x1x2 0:

29.17
Showthatthefollowinglinearprogramisunbounded:
maximize x1 x2
sujetoa
2x1 do x2 1
x1 2x2 2
x1x2 0:

29.18
Supposethatwehaveagenerallinearprogramwithnvariablesandmconstraints,
andsupposethatweconvertitintostandardform.Giveanupperboundonthe
numberofvariablesandconstraintsintheresultinglinearprogram.

29.19
Giveanexampleofalinearprogramforwhichthefeasibleregionisnotbounded,
buttheoptimalobjectivevalueisfinite.

Pgina280

29.2Formulatingproblemsaslinearprograms 859

29.2Formulatingproblemsaslinearprograms

Althoughweshallfocusonthesimplexalgorithminthischapter,itisalsoimpor
tanttobeabletorecognizewhenwecanformulateaproblemasalinearprogram.
Oncewecastaproblemasapolynomialsizedlinearprogram,wecansolveit
inpolynomialtimebytheellipsoidalgorithmorinteriorpointmethods.Varios
linearprogrammingsoftwarepackagescansolveproblemsefficiently,sothatonce
theproblemisintheformofalinearprogram,suchapackagecansolveit.
Weshalllookatseveralconcreteexamplesoflinearprogrammingproblems.Nosotros
startwithtwoproblemsthatwehavealreadystudied:thesinglesourceshortest
pathsproblem(seeChapter24)andthemaximumflowproblem(seeChapter26).
Wethendescribetheminimumcostflowproblem.Althoughtheminimumcost
flowproblemhasapolynomialtimealgorithmthatisnotbasedonlinearprogram
ming,wewon'tdescribethealgorithm.Finally,wedescribethemulticommodity
flowproblem,forwhichtheonlyknownpolynomialtimealgorithmisbasedon
linearprogramming.
WhenwesolvedgraphproblemsinPartVI,weusedattributenotation,such
as:dand.u/:f.Linearprogramstypicallyusesubscriptedvariablesrather
thanobjectswithattachedattributes,however.Therefore,whenweexpressvari
ablesinlinearprograms,weshallindicateverticesandedgesthroughsubscripts.
Forexample,wedenotetheshortestpathweightforvertexnotby:dbutbyd.
Similarly,wedenotetheflowfromvertexutovertexnotby.u/:fbutbyfu.
Forquantitiesthataregivenasinputstoproblems,suchasedgeweightsorcapac
ities,weshallcontinuetousenotationssuchaswu/andcu:/.

Shortestpaths
Wecanformulatethesinglesourceshortestpathsproblemasalinearprogram.
Inthissection,weshallfocusonhowtoformulatethesinglepairshortestpath
problem,leavingtheextensiontothemoregeneralsinglesourceshortestpaths
problemasExercise29.23.
Inthesinglepairshortestpathproblem,wearegivenaweighted,directedgraph
GD.VE/,withweightfunctionwWE!Rmappingedgestorealvalued
weights,asourcevertexs,anddestinationvertext.Wewishtocomputethe
valuedt,whichistheweightofashortestpathfromstot.Toexpressthisprob
lemasalinearprogram,weneedtodetermineasetofvariablesandconstraintsthat
definewhenwehaveashortestpathfromstot.Fortunately,theBellmanFordal
gorithmdoesexactlythis.WhentheBellmanFordalgorithmterminates,ithas
https://translate.googleusercontent.com/translate_f 173/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
computed,foreachvertex,avalued(usingsubscriptnotationhereratherthan
attributenotation)suchthatforeachedge.u/2E,wehavedduCw.u/.

Page281

860 Chapter29LinearProgramming

ThesourcevertexinitiallyreceivesavaluedsD0,whichneverchanges.As
weobtainthefollowinglinearprogramtocomputetheshortestpathweightfroms
tot:
maximizedt (29.44)
sujetoa
re duCwu/foreachedge.u/2E (29.45)
ds D0: (29.46)
Youmightbesurprisedthatthislinearprogrammaximizesanobjectivefunction
whenitissupposedtocomputeshortestpaths.Wedonotwanttominimizethe
norte
objectivefunction,sincethensetting dD0forall2Vwouldyieldanoptimal
solutiontothelinearprogramwithoutsolvingtheshortestpathsproblem.Nosotros
maximizebecauseanoptimalsolutiontotheshortestpathsproblemsetseach
norte
re
tominuW.u/2E dnorte
uCwu/ norte
,sothat disthelargestvaluethatislessthanor

equaltoallofthevaluesintheset norte
duCwu/ .Wewanttomaximized
forallverticesonashortestpathfromstotsubjecttotheseconstraintsonall
vertices,andmaximizingdtachievesthisgoal.
ThislinearprogramhasjVjvariablesd,oneforeachvertex 2V.Italso
hasjEjC1constraints:oneforeachedge,plustheadditionalconstraintthatthe
sourcevertex'sshortestpathweightalwayshasthevalue0.

Maximumflow
Next,weexpressthemaximumflowproblemasalinearprogram.Recallthatwe
aregivenadirectedgraphGD.VE/inwhicheachedge.u/2Ehasa
nonnegativecapacitycu/ 0,andtwodistinguishedvertices:asourcesand
asinkt.AsdefinedinSection26.1,aflowisanonnegativerealvaluedfunction
fWV V!Rthatsatisfiesthecapacityconstraintandflowconservation.UN
maximumflowisaflowthatsatisfiestheseconstraintsandmaximizestheflow
value,whichisthetotalflowcomingoutofthesourceminusthetotalflowintothe
fuente.Aflow,therefore,satisfieslinearconstraints,andthevalueofaflowisa
linearfunction.Recallingalsothatweassumethatcu/D0if.u/62Eand
thattherearenoantiparalleledges,wecanexpressthemaximumflowproblemas
alinearprogram:
x x
maximize fs fs (29.47)
2V 2V
sujetoa
x fu cu/foreachu2V
x (29.48)
fu re fu foreachu2V fstg (29.49)
2V 2V
fu 0 foreachu2V: (29.50)

Pgina282

29.2Formulatingproblemsaslinearprograms 861

ThislinearprogramhasjVj 2 variables,correspondingtotheflowbetweeneach
pairofvertices,andithas2jVj 2 CjVj2constraints.
Itisusuallymoreefficienttosolveasmallersizedlinearprogram.Ellineal
programin(29.47)(29.50)has,foreaseofnotation,aflowandcapacityof0for
eachpairofverticesuwith.u/62E.Itwouldbemoreefficienttorewritethe
linearprogramsothatithasOVCE/constraints.Exercise29.25asksyouto
doso.

Minimumcostflow

Inthissection,wehaveusedlinearprogrammingtosolveproblemsforwhichwe
alreadyknewefficientalgorithms.Infact,anefficientalgorithmdesignedspecif
icallyforaproblem,suchasDijkstra'salgorithmforthesinglesourceshortest
pathsproblem,orthepushrelabelmethodformaximumflow,willoftenbemore
efficientthanlinearprogramming,bothintheoryandinpractice.
Therealpoweroflinearprogrammingcomesfromtheabilitytosolvenewprob
ProblemasRecalltheproblemfacedbythepoliticianinthebeginningofthischapter.
Theproblemofobtainingasufficientnumberofvotes,whilenotspendingtoo
muchmoney,isnotsolvedbyanyofthealgorithmsthatwehavestudiedinthis
book,yetwecansolveitbylinearprogramming.Booksaboundwithsuchreal
https://translate.googleusercontent.com/translate_f 174/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
worldproblemsthatlinearprogrammingcansolve.Linearprogrammingisalso
particularlyusefulforsolvingvariantsofproblemsforwhichwemaynotalready
knowofanefficientalgorithm.
Consider,forexample,thefollowinggeneralizationofthemaximumflowprob
LemSupposethat,inadditiontoacapacitycu/foreachedge.u/,weare
givenarealvaluedcostau/.Asinthemaximumflowproblem,weassumethat
cu/D0if.u/62E,andthattherearenoantiparalleledges.Ifwesendfu
unitsofflowoveredge.u/,weincuracostofau/fu.Wearealsogivena
flowdemandd.Wewishtosenddunitsofflowfromstotwhileminimizingthe
PAG
totalcost .u/2Eau/fuincurredbytheflow.Thisproblemisknownasthe
minimumcostflowproblem.
Figure29.3(a)showsanexampleoftheminimumcostflowproblem.Wewish
tosend4unitsofflowfromstotwhileincurringtheminimumtotalcost.Alguna
particularlegalflow,thatis,afunctionfsatisfyingconstraints(29.48)(29.49),
PAG
incursatotalcostof
.u/2Eau/fu.Wewishtofindtheparticular4unit
flowthatminimizesthiscost.Figure29.3(b)showsanoptimalsolution,withtotal
PAG
cost .u/2Eau/fuD.22/C.52/C.31/C.71/C.13/D27:
Therearepolynomialtimealgorithmsspecificallydesignedfortheminimum
costflowproblem,buttheyarebeyondthescopeofthisbook.Wecan,however,
expresstheminimumcostflowproblemasalinearprogram.Thelinearprogram
lookssimilartotheoneforthemaximumflowproblemwiththeadditionalcon

Pgina283

862 Chapter29LinearProgramming

do=2 1/2
c=5 x un=7 2/5 x un=7
un=2 un=2
S c=1 T S 1/1 T
a=3 a=3
do=2 2/2
un=5 Y c=4 un=5 Y 3/4
un=1 un=1
(un) (segundo)

Figure29.3(a)Anexampleofaminimumcostflowproblem.Wedenotethecapacitiesbycand
thecostsbya.Vertexsisthesourceandvertextisthesink,andwewishtosend4unitsofflow
fromstot.(b)Asolutiontotheminimumcostflowprobleminwhich4unitsofflowaresentfroms
tot.Foreachedge,theflowandcapacityarewrittenasflow/capacity.

straintthatthevalueoftheflowbeexactlydunits,andwiththenewobjective
functionofminimizingthecost:
x
minimize au/fu (29.51)
sujetoa .u/2E
x x fu cu/foreachu2V
fu fu D0 foreachu2V fstg
x2V x2V
fs fs Dd
2V 2V
fu 0 foreachu2V: (29.52)

Multicommodityflow
Asafinalexample,weconsideranotherflowproblem.SupposethattheLucky
PuckcompanyfromSection26.1decidestodiversifyitsproductlineandship
notonlyhockeypucks,butalsohockeysticksandhockeyhelmets.Eachpieceof
equipmentismanufacturedinitsownfactory,hasitsownwarehouse,andmust
beshipped,eachday,fromfactorytowarehouse.Thesticksaremanufacturedin
VancouverandmustbeshippedtoSaskatoon,andthehelmetsaremanufacturedin
EdmontonandmustbeshippedtoRegina.Thecapacityoftheshippingnetwork
doesnotchange,however,andthedifferentitems,orcommodities,mustsharethe
samenetwork.
Thisexampleisaninstanceofamulticommodityflowproblem.Inthisproblem,
weareagaingivenadirectedgraphGD.VE/inwhicheachedge.u/2E
hasanonnegativecapacitycu/ 0.Asinthemaximumflowproblem,weim
plicitlyassumethatcu/D0for.u/62E,andthatthegraphhasnoantipar

Page284

29.2Formulatingproblemsaslinearprograms 863

https://translate.googleusercontent.com/translate_f 175/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
alleledges.Inaddition,wearegivenkdifferentcommodities,K1K2:::Kk,
wherewespecifycommodityibythetripleKiD.sitidi/.Here,vertexsiis
thesourceofcommodityi,vertextiisthesinkofcommodityi,anddiisthede
mandforcommodityi,whichisthedesiredflowvalueforthecommodityfromsi
toti.Wedefineaflowforcommodityi,denotedbyfi,(sothatfiuistheflowof
commodityifromvertexutovertex)tobearealvaluedfunctionthatsatisfies
theflowconservationandcapacityconstraints.Wenowdefinefu,theaggregate
Pk
flow,tobethesumofthevariouscommodityflows,sothatfuD iD1fiu. los
aggregateflowonedge.u/mustbenomorethanthecapacityofedge.u/.
Wearenottryingtominimizeanyobjectivefunctioninthisproblemnecesitamos
onlydeterminewhethersuchaflowexists.Thus,wewritealinearprogramwitha
nullobjectivefunction:
minimize 0
sujetoa
xK
fiu cu/foreachu2V
x xID1
fiu fiu D0 foreachiD12:::kand
2V 2V foreachu2V fsitig
x x
fis
i fisi Ddi foreachiD12:::k
2V 2V
fiu 0 foreachu2Vand
foreachiD12:::k:
Theonlyknownpolynomialtimealgorithmforthisproblemexpressesitasalinear
programandthensolvesitwithapolynomialtimelinearprogrammingalgorithm.

Exercises

29.21
Putthesinglepairshortestpathlinearprogramfrom(29.44)(29.46)intostandard
formar.

29.22
Writeoutexplicitlythelinearprogramcorrespondingtofindingtheshortestpath
fromnodestonodeyinFigure24.2(a).

29.23
Inthesinglesourceshortestpathsproblem,wewanttofindtheshortestpath
weightsfromasourcevertexstoallvertices 2V.GivenagraphG,writea

Pgina285

864 Chapter29LinearProgramming

linearprogramforwhichthesolutionhasthepropertythatdistheshortestpath
weightfromstoforeachvertex2V.

29.24
Writeoutexplicitlythelinearprogramcorrespondingtofindingthemaximumflow
inFigure26.1(a).

29.25
Rewritethelinearprogramformaximumflow(29.47)(29.50)sothatitusesonly
OVCE/constraints.

29.26
Writealinearprogramthat,givenabipartitegraphGD.VE/,solvesthemaxi
mumbipartitematchingproblem.

29.27
Intheminimumcostmulticommodityflowproblem,wearegivendirectedgraph
GD.VE/inwhicheachedge.u/2Ehasanonnegativecapacitycu/ 0
andacostau/.Asinthemulticommodityflowproblem,wearegivenkdif
ferentcommodities,K1K2:::Kk,wherewespecifycommodityibythetriple
KiD.sitidi/.Wedefinetheflowfiforcommodityiandtheaggregateflowfu
onedge.u/asinthemulticommodityflowproblem.Afeasibleflowisone
inwhichtheaggregateflowoneachedge.u/isnomorethanthecapacityof
PAG
edge.u/.Thecostofaflowis u2Vau/fu,andthegoalistofindthe
feasibleflowofminimumcost.Expressthisproblemasalinearprogram.

29.3Thesimplexalgorithm

Thesimplexalgorithmistheclassicalmethodforsolvinglinearprograms.Incon
trasttomostoftheotheralgorithmsinthisbook,itsrunningtimeisnotpolynomial
https://translate.googleusercontent.com/translate_f 176/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
intheworstcase.Itdoesyieldinsightintolinearprograms,however,andisoften
remarkablyfastinpractice.
Inadditiontohavingageometricinterpretation,describedearlierinthischapter,
thesimplexalgorithmbearssomesimilaritytoGaussianelimination,discussedin
Section28.1.Gaussianeliminationbeginswithasystemoflinearequalitieswhose
solutionisunknown.Ineachiteration,werewritethissysteminanequivalent
formthathassomeadditionalstructure.Aftersomenumberofiterations,wehave
rewrittenthesystemsothatthesolutionissimpletoobtain.Thesimplexalgo
rithmproceedsinasimilarmanner,andwecanviewitasGaussianeliminationfor
inequalities.

Pgina286

29.3Thesimplexalgorithm 865

Wenowdescribethemainideabehindaniterationofthesimplexalgorithm.
Associatedwitheachiterationwillbeabasicsolutionthatwecaneasilyobtain
fromtheslackformofthelinearprogram:seteachnonbasicvariableto0and
computethevaluesofthebasicvariablesfromtheequalityconstraints.Aniteration
convertsoneslackformintoanequivalentslackform.Theobjectivevalueofthe
associatedbasicfeasiblesolutionwillbenolessthanthatatthepreviousiteration,
andusuallygreater.Toachievethisincreaseintheobjectivevalue,wechoosea
nonbasicvariablesuchthatifweweretoincreasethatvariable'svaluefrom0,then
theobjectivevaluewouldincrease,too.Theamountbywhichwecanincrease
thevariableislimitedbytheotherconstraints.Inparticular,weraiseituntilsome
basicvariablebecomes0.Wethenrewritetheslackform,exchangingtheroles
ofthatbasicvariableandthechosennonbasicvariable.Althoughwehaveuseda
particularsettingofthevariablestoguidethealgorithm,andweshalluseitinour
proofs,thealgorithmdoesnotexplicitlymaintainthissolution.Itsimplyrewrites
thelinearprogramuntilanoptimalsolutionbecomesobvious.

Anexampleofthesimplexalgorithm
Webeginwithanextendedexample.Considerthefollowinglinearprogramin
standardform:
maximize3x1 do x2 C2x3 (29.53)
sujetoa
x1 do x2 C3x3 30 (29.54)
2x1 C2x2 C5x3 24 (29.55)
4x1 do x2 C2x3 36 (29.56)
x1x2x3 0: (29.57)
Inordertousethesimplexalgorithm,wemustconvertthelinearprograminto
slackformwesawhowtodosoinSection29.1.Inadditiontobeinganalgebraic
manipulation,slackisausefulalgorithmicconcept.RecallingfromSection29.1
thateachvariablehasacorrespondingnonnegativityconstraint,wesaythatan
equalityconstraintistightforaparticularsettingofitsnonbasicvariablesifthey
causetheconstraint'sbasicvariabletobecome0.Similarly,asettingofthenon
basicvariablesthatwouldmakeabasicvariablebecomenegativeviolatesthat
constraint.Thus,theslackvariablesexplicitlymaintainhowfareachconstraintis
frombeingtight,andsotheyhelptodeterminehowmuchwecanincreasevalues
ofnonbasicvariableswithoutviolatinganyconstraints.
Associatingtheslackvariablesx4,x5,andx6withinequalities(29.54)(29.56),
respectively,andputtingthelinearprogramintoslackform,weobtain

Pgina287

866 Chapter29LinearProgramming

D 3x1 do x2 C2x3 (29.58)


x4 D30 x1 x2 3x3 (29.59)
x5 D24 2x1 2x2 5x3 (29.60)
x6 D36 4x1 x2 2x3: (29.61)
Thesystemofconstraints(29.59)(29.61)has3equationsand6variables.Alguna
settingofthevariablesx1,x2,andx3definesvaluesforx4,x5,andx6porlotanto,
wehaveaninfinitenumberofsolutionstothissystemofequations.Asolutionis
feasibleifallofx1x2:::x6arenonnegative,andtherecanbeaninfinitenum
beroffeasiblesolutionsaswell.Theinfinitenumberofpossiblesolutionstoa
systemsuchasthisonewillbeusefulinlaterproofs.Wefocusonthebasicsolu

https://translate.googleusercontent.com/translate_f 177/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
tion:setallthe(nonbasic)variablesontherighthandsideto0andthencompute
thevaluesofthe(basic)variablesonthelefthandside.Inthisexample,theba
sicsolutionis.Nx1Nx2:::Nx6/D.000302436/andithasobjectivevalue
D.30/C.10/C.20/D0.ObservethatthisbasicsolutionsetsNxiDbi
foreachi2B.Aniterationofthesimplexalgorithmrewritesthesetofequations
andtheobjectivefunctionsoastoputadifferentsetofvariablesontheright
handside.Thus,adifferentbasicsolutionisassociatedwiththerewrittenproblem.
Weemphasizethattherewritedoesnotinanywaychangetheunderlyinglinear
programmingproblemtheproblematoneiterationhastheidenticalsetoffeasible
solutionsastheproblematthepreviousiteration.Theproblemdoes,however,
haveadifferentbasicsolutionthanthatofthepreviousiteration.
Ifabasicsolutionisalsofeasible,wecallitabasicfeasiblesolution.Aswerun
thesimplexalgorithm,thebasicsolutionisalmostalwaysabasicfeasiblesolution.
WeshallseeinSection29.5,however,thatforthefirstfewiterationsofthesimplex
algorithm,thebasicsolutionmightnotbefeasible.
Ourgoal,ineachiteration,istoreformulatethelinearprogramsothatthebasic
solutionhasagreaterobjectivevalue.Weselectanonbasicvariablexewhose
coefficientintheobjectivefunctionispositive,andweincreasethevalueofxeas
muchaspossiblewithoutviolatinganyoftheconstraints.Thevariablexebecomes
basic,andsomeothervariablexlbecomesnonbasic.Thevaluesofotherbasic
variablesandoftheobjectivefunctionmayalsochange.
Tocontinuetheexample,let'sthinkaboutincreasingthevalueofx1.Comonosotros
increasex1,thevaluesofx4,x5,andx6alldecrease.Becausewehaveanonnega
tivityconstraintforeachvariable,wecannotallowanyofthemtobecomenegative.
Ifx1increasesabove30,thenx4becomesnegative,andx5andx6becomenega
tivewhenx1increasesabove12and9,respectively.Thethirdconstraint(29.61)is
thetightestconstraint,anditlimitshowmuchwecanincreasex1.Therefore,we
switchtherolesofx1andx6.Wesolveequation(29.61)forx1andobtain
x2 x3 x6
x1D9 : (29.62)
4 2 4

Pgina288

29.3Thesimplexalgorithm 867

Torewritetheotherequationswithx6ontherighthandside,wesubstituteforx1
usingequation(29.62).Doingsoforequation(29.59),weobtain
x4 D30x1 x2 3x3 UN
x2 x3 x6
D30 9 x2 3x3
4 2 4
3x2 5x3 x6
D21 do : (29.63)
4 2 4
Similarly,wecombineequation(29.62)withconstraint(29.60)andwithobjective
function(29.58)torewriteourlinearprograminthefollowingform:
x2 x3 3x6
D27C do (29.64)
4 2 4
x2 x3 x6
x1 re 9 (29.65)
4 2 4
3x2 5x3 x6
x4 D21 do (29.66)
4 2 4
3x2 x6
x5 re 6 4x3 do : (29.67)
2 2
Wecallthisoperationapivot.Asdemonstratedabove,apivotchoosesanonbasic
variablexe,calledtheenteringvariable,andabasicvariablexl,calledtheleaving
variable,andexchangestheirroles.
Thelinearprogramdescribedinequations(29.64)(29.67)isequivalenttothe
linearprogramdescribedinequations(29.58)(29.61).Weperformtwooperations
inthesimplexalgorithm:rewriteequationssothatvariablesmovebetweentheleft
handsideandtherighthandside,andsubstituteoneequationintoanother.Elprimero
operationtriviallycreatesanequivalentproblem,andthesecond,byelementary
linearalgebra,alsocreatesanequivalentproblem.(SeeExercise29.33.)
Todemonstratethisequivalence,observethatouroriginalbasicsolution.00
0302436/satisfiesthenewequations(29.65)(29.67)andhasobjectivevalue
27C.1=4/0C.1=2/0.3=4/36D0.Thebasicsolutionassociatedwiththe
newlinearprogramsetsthenonbasicvaluesto0andis.9002160/,withob
jectivevalueD27.Simplearithmeticverifiesthatthissolutionalsosatisfies
equations(29.59)(29.61)and,whenpluggedintoobjectivefunction(29.58),has
objectivevalue.39/C.10/C.20/D27.
Continuingtheexample,wewishtofindanewvariablewhosevaluewewishto
incrementar.Wedonotwanttoincreasex6,sinceasitsvalueincreases,theobjective
valuedecreases.Wecanattempttoincreaseeitherx2orx3letuschoosex3.Cmo
farcanweincreasex3withoutviolatinganyoftheconstraints?Constraint(29.65)
limitsitto18,constraint(29.66)limitsitto42=5,andconstraint(29.67)limits
itto3=2.Thethirdconstraintisagainthetightestone,andthereforewerewrite
thethirdconstraintsothatx3isonthelefthandsideandx5isontherighthand

https://translate.googleusercontent.com/translate_f 178/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy

Pgina289

868 Chapter29LinearProgramming

side.Wethensubstitutethisnewequation,x3D3=23x2=8x5=4Cx6=8,into
equations(29.64)(29.66)andobtainthenew,butequivalent,system
111 x2 x5 11x6
D do (29.68)
4 diecisis 8 diecisis
33 x2 x5 5x6
x1 re do (29.69)
4 diecisis 8 diecisis
3 3x2 x5 x6
x3 re do (29.70)
2 8 4 8
69 3x2 5x5 x6
x4 re do do : (29.71)
4 diecisis 8 diecisis
Thissystemhastheassociatedbasicsolution.33=403=269=400/,withob
jectivevalue111=4.Nowtheonlywaytoincreasetheobjectivevalueistoin
creasex2.Thethreeconstraintsgiveupperboundsof132,4,and1,respectively.
(Wegetanupperboundof1fromconstraint(29.71)because,asweincreasex2,
thevalueofthebasicvariablex4increasesalso.Thisconstraint,therefore,places
norestrictiononhowmuchwecanincreasex2.)Weincreasex2to4,anditbe
comesnonbasic.Thenwesolveequation(29.70)forx2andsubstituteintheother
equationstoobtain
x3 x5 2x6
D28 (29.72)
6 6 3
x3 x5 x6
x1 re 8C do (29.73)
6 6 3
8x3 2x5 x6
x2 re 4 do (29.74)
3 3 3
x3 x5
x4 D18 do : (29.75)
2 2
Atthispoint,allcoefficientsintheobjectivefunctionarenegative.Asweshallsee
laterinthischapter,thissituationoccursonlywhenwehaverewrittenthelinear
programsothatthebasicsolutionisanoptimalsolution.Thus,forthisproblem,
thesolution.8401800/,withobjectivevalue28,isoptimal.Wecannow
returntoouroriginallinearprogramgivenin(29.53)(29.57).Theonlyvariables
intheoriginallinearprogramarex1,x2,andx3,andsooursolutionisx1D8,
x2D4,andx3D0,withobjectivevalue.38/C.14/C.20/D28.Note
thatthevaluesoftheslackvariablesinthefinalsolutionmeasurehowmuchslack
remainsineachinequality.Slackvariablex4is18,andininequality(29.54),the
lefthandside,withvalue8C4C0D12,is18lessthantherighthandsideof30.
Slackvariablesx5andx6are0andindeed,ininequalities(29.55)and(29.56),
thelefthandandrighthandsidesareequal.Observealsothateventhoughthe
coefficientsintheoriginalslackformareintegral,thecoefficientsintheother
linearprogramsarenotnecessarilyintegral,andtheintermediatesolutionsarenot

Pgina290

29.3Thesimplexalgorithm 869

necessarilyintegral.Furthermore,thefinalsolutiontoalinearprogramneednot
beintegralitispurelycoincidentalthatthisexamplehasanintegralsolution.

Pivoting
Wenowformalizetheprocedureforpivoting.TheprocedurePIVOTtakesasin
putaslackform,givenbythetuple.NBAsegundoc/,theindexloftheleav
ingvariablexl,andtheindexeoftheenteringvariablexe.Itreturnsthetuple
Y
.yNyByA
segundoycy/describingthenewslackform.(Recallagainthattheentriesof
themnmatricesAandyAareactuallythenegativesofthecoefficientsthatappear
intheslackform.)

PIVOT.NBAbcle/
1//Computethecoefficientsoftheequationfornewbasicvariablexe.
2letyAbeanewmnmatrix
3 b YeDbl=ale
4foreachj2N feg
5 yaejDalj=ale
6yaelD1=ale
7//Computethecoefficientsoftheremainingconstraints.
8foreachi2Bflg
9 YiDbi
b Ye
aie b

https://translate.googleusercontent.com/translate_f 179/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
10
11 foreachj2N
yaijDaij afeg
ie yaej

12 yailDaieyael
13//Computetheobjectivefunction.
14yDCce Ye
b
15foreachj2N feg
diecisis ycjDcj ceyaej
17yclDceyael
18//Computenewsetsofbasicandnonbasicvariables.
19yNDN feg[flg
20yBDBflg[feg
Y
21return.yNyByAsegundoycy/

PIVOTworksasfollows.Lines36computethecoefficientsinthenewequation
forxebyrewritingtheequationthathasxlonthelefthandsidetoinsteadhavexe
onthelefthandside.Lines812updatetheremainingequationsbysubstituting
therighthandsideofthisnewequationforeachoccurrenceofxe.Lines1417
dothesamesubstitutionfortheobjectivefunction,andlines19and20updatethe

Page291

870 Chapter29LinearProgramming

setsofnonbasicandbasicvariables.Line21returnsthenewslackform.Asgiven,
ifaleD0,PIVOTwouldcauseanerrorbydividingby0,butasweshallseeinthe
proofsofLemmas29.2and29.12,wecallPIVOTonlywhenale0.
WenowsummarizetheeffectthatPIVOThasonthevaluesofthevariablesin
thebasicsolution.

Lemma29.1
ConsideracalltoPIVOT.NBAbcle/inwhichale0.Letthevalues
Y
returnedfromthecallbe.yNyByA
segundoycy/,andletNxdenotethebasicsolutionafter
thecall.Then
1.NxjD0foreachj2yN.
2.NxeDbl=ale.
Yeforeachi2yBfeg.
3.NxiDbi aie b

ProofThefirststatementistruebecausethebasicsolutionalwayssetsallnon
basicvariablesto0.Whenweseteachnonbasicvariableto0inaconstraint
x
xiDybi yaijxj
j2yN
wehavethatNxiDybiforeachi2yB.Sincee2yB,line3ofPIVOTgives
NxeDybeDbl=ale
whichprovesthesecondstatement.Similarly,usingline9foreachi2yBfeg,
wehave
Ye
NxiDybiDbi aie b
whichprovesthethirdstatement.

Theformalsimplexalgorithm
Wearenowreadytoformalizethesimplexalgorithm,whichwedemonstratedby
ejemplo.Thatexamplewasaparticularlyniceone,andwecouldhavehadseveral
otherissuestoaddress:
Howdowedeterminewhetheralinearprogramisfeasible?
Whatdowedoifthelinearprogramisfeasible,buttheinitialbasicsolutionis
notfeasible?
Howdowedeterminewhetheralinearprogramisunbounded?
Howdowechoosetheenteringandleavingvariables?

Pgina292

29.3Thesimplexalgorithm 871

InSection29.5,weshallshowhowtodeterminewhetheraproblemisfeasible,
andifso,howtofindaslackforminwhichtheinitialbasicsolutionisfeasible.
Therefore,letusassumethatwehaveaprocedureINITIALIZESIMPLEX.Abc/

https://translate.googleusercontent.com/translate_f 180/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
thattakesasinputalinearprograminstandardform,thatis,anm
AD.a ij/,anmvectorbD.bi/,andannvectorcD.cj/.Iftheproblemis nmatrix

infeasible,theprocedurereturnsamessagethattheprogramisinfeasibleandthen
Termina.Otherwise,theprocedurereturnsaslackformforwhichtheinitial
basicsolutionisfeasible.
TheprocedureSIMPLEXtakesasinputalinearprograminstandardform,asjust
Descrito.ItreturnsannvectorNxD.Nxj/thatisanoptimalsolutiontothelinear
programdescribedin(29.19)(29.21).

SIMPLEX.Abc/
1.NBAsegundoc/DINITIALIZESIMPLEX.Abc/
2letbeanewvectoroflengthn
3whilesomeindexj2Nhascj>0
4 chooseanindexe2Nforwhichce>0
5 foreachindexi2B
6 ifaie>0
7 iDbi=aie

8 elseiD1
9 chooseanindexl2Bthatminimizesi
10 ifl==1
11 returnunbounded
12 else.NBAbc/DPIVOT.NBAbcle/
13foriD1ton
14 ifi2B
15 NxiDbi
diecisis elseNxiD0
17return.Nx1Nx2:::Nxn/

TheSIMPLEXprocedureworksasfollows.Inline1,itcallstheprocedure
INITIALIZESIMPLEX.Abc/,describedabove,whicheitherdeterminesthatthe
linearprogramisinfeasibleorreturnsaslackformforwhichthebasicsolutionis
feasible.Thewhileloopoflines312formsthemainpartofthealgorithm.Ifall
coefficientsintheobjectivefunctionarenegative,thenthewhileloopterminates.
Otherwise,line4selectsavariablexe,whosecoefficientintheobjectivefunction
ispositive,astheenteringvariable.Althoughwemaychooseanysuchvariableas
theenteringvariable,weassumethatweusesomeprespecifieddeterministicrule.
Next,lines59checkeachconstraintandpicktheonethatmostseverelylimits
theamountbywhichwecanincreasexewithoutviolatinganyofthenonnegativ

Pgina293

872 Chapter29LinearProgramming

ityconstraintsthebasicvariableassociatedwiththisconstraintisxl.Again,we
arefreetochooseoneofseveralvariablesastheleavingvariable,butweassume
thatweusesomeprespecifieddeterministicrule.Ifnoneoftheconstraintslim
itstheamountbywhichtheenteringvariablecanincrease,thealgorithmreturns
unboundedinline11.Otherwise,line12exchangestherolesoftheentering
andleavingvariablesbycallingPIVOT.NBAbcle/,asdescribedabove.
Lines1316computeasolutionNx1Nx2:::Nxnfortheoriginallinearprogramming
variablesbysettingallthenonbasicvariablesto0andeachbasicvariableNxitobi,
andline17returnsthesevalues.
ToshowthatSIMPLEXiscorrect,wefirstshowthatifSIMPLEXhasaninitial
feasiblesolutionandeventuallyterminates,theniteitherreturnsafeasiblesolution
ordeterminesthatthelinearprogramisunbounded.Then,weshowthatSIMPLEX
Termina.Finally,inSection29.4(Theorem29.10)weshowthatthesolution
returnedisoptimal.

Lemma29.2
Givenalinearprogram.Asegundoc/,supposethatthecalltoINITIALIZESIMPLEXin
line1ofSIMPLEXreturnsaslackformforwhichthebasicsolutionisfeasible.
ThenifSIMPLEXreturnsasolutioninline17,thatsolutionisafeasiblesolutionto
thelinearprogram.IfSIMPLEXreturnsunboundedinline11,thelinearprogram
isunbounded.

ProofWeusethefollowingthreepartloopinvariant:
Atthestartofeachiterationofthewhileloopoflines312,
1.theslackformisequivalenttotheslackformreturnedbythecallof
INITIALIZESIMPLEX,
2.foreachi2B,wehavebi 0,and
3.thebasicsolutionassociatedwiththeslackformisfeasible.

Initialization:Theequivalenceoftheslackformsistrivialforthefirstitera
Cin.Weassume,inthestatementofthelemma,thatthecalltoINITIALIZE
SIMPLEXinline1ofSIMPLEXreturnsaslackformforwhichthebasicsolution
isfeasible.Thus,thethirdpartoftheinvariantistrue.Becausethebasicso
https://translate.googleusercontent.com/translate_f 181/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
lutionisfeasible,eachbasicvariablexiisnonnegative.Furthermore,sincethe
basicsolutionsetseachbasicvariablexitobi,wehavethatbi 0forall
i2B.Thus,thesecondpartoftheinvariantholds.
Maintenance:Weshallshowthateachiterationofthewhileloopmaintainsthe
loopinvariant,assumingthatthereturnstatementinline11doesnotexecute.
Weshallhandlethecaseinwhichline11executeswhenwediscusstermination.

Page294

29.3Thesimplexalgorithm 873

Aniterationofthewhileloopexchangestheroleofabasicandanonbasic
variablebycallingthePIVOTprocedure.ByExercise29.33,theslackformis
equivalenttotheonefromthepreviousiterationwhich,bytheloopinvariant,
isequivalenttotheinitialslackform.
Wenowdemonstratethesecondpartoftheloopinvariant.Weassumethatat
thestartofeachiterationofthewhileloop,bi 0foreachi2B,andweshall
showthattheseinequalitiesremaintrueafterthecalltoPIVOTinline12.Since
theonlychangestothevariablesbiandthesetBofbasicvariablesoccurinthis
assignment,itsufficestoshowthatline12maintainsthispartoftheinvariant.
Weletbi,aij,andBrefertovaluesbeforethecallofPIVOT,and Yireferto
b
valuesreturnedfromPIVOT.
First,weobservethat b Ye 0becausebl 0bytheloopinvariant,ale>0by
lines6and9ofSIMPLEX,and b YeDbl=alebyline3ofPIVOT.
Fortheremainingindicesi2Bflg,wehavethat
Yi Dbi
b Ye
aie b (byline9ofPIVOT)
Dbi aie.bl=ale/(byline3ofPIVOT). (29.76)
Wehavetwocasestoconsider,dependingonwhetheraie>0oraie0.
Ifaie>0,thensincewechoselsuchthat

bl=alebi=aie foralli2B (29.77)

wehave
Yi Dbi
b aie.bl=ale/(byequation(29.76))
bi aie.bi=aie/(byinequality(29.77))
Dbi bi
D0
Yi
b
yporlotanto 0.Ifaie0,thenbecauseale,bi,andblareallnonnegative,
equation(29.76)impliesthat b Yimustbenonnegative,too.
Wenowarguethatthebasicsolutionisfeasible,ie,thatallvariableshavenon
negativevalues.Thenonbasicvariablesaresetto0andthusarenonnegative.
Eachbasicvariablexiisdefinedbytheequation
x
xiDbi aijxj:
j2N
ThebasicsolutionsetsNxiDbi.Usingthesecondpartoftheloopinvariant,we
concludethateachbasicvariableNxiisnonnegative.

Pgina295

874 Chapter29LinearProgramming

Termination:Thewhileloopcanterminateinoneoftwoways.Ifitterminates
becauseoftheconditioninline3,thenthecurrentbasicsolutionisfeasibleand
line17returnsthissolution.Theotherwayitterminatesisbyreturningun
boundedinline11.Inthiscase,foreachiterationoftheforloopinlines58,
whenline6isexecuted,wefindthata
Un ie 0.ConsiderthesolutionNxdefinedas

1 ifiDe
NxiD 0 PAG ifi2N feg
bi j2NaijNxj ifi2B:
Wenowshowthatthissolutionisfeasible,ie,thatallvariablesarenonneg
ative.ThenonbasicvariablesotherthanNxeare0,andNxeD1>0thusall
nonbasicvariablesarenonnegative.ForeachbasicvariableNxi,wehave
x
Nxi Dbi aijNxj

https://translate.googleusercontent.com/translate_f 182/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
j2N
Dbi aieNxe:
Theloopinvariantimpliesthatbi 0,andwehaveaie0andNxeD1>0.
Thus,Nxi 0.
NowweshowthattheobjectivevalueforthesolutionNxisunbounded.De
equation(29.42),theobjectivevalueis
x
D do cjNxj
j2N
re CceNxe:
Sincece>0(byline4ofSIMPLEX)andNxeD1,theobjectivevalueis1,
andthusthelinearprogramisunbounded.

ItremainstoshowthatSIMPLEXterminates,andwhenitdoesterminate,the
solutionitreturnsisoptimal.Section29.4willaddressoptimality.Wenowdiscuss
termination.

Terminacin
Intheexamplegiveninthebeginningofthissection,eachiterationofthesimplex
algorithmincreasedtheobjectivevalueassociatedwiththebasicsolution.AsEx
ercise29.32asksyoutoshow,noiterationofSIMPLEXcandecreasetheobjective
valueassociatedwiththebasicsolution.Unfortunately,itispossiblethatanitera
tionleavestheobjectivevalueunchanged.Thisphenomenoniscalleddegeneracy,
andweshallnowstudyitingreaterdetail.

Pgina296

29.3Thesimplexalgorithm 875

Theassignmentinline14ofPIVOT,yDCce Ye,changestheobjectivevalue.
b
SinceSIMPLEXcallsPIVOTonlywhence>0,theonlywayfortheobjective
valuetoremainunchanged(ie,yD)isfor Yetobe0.Thisvalueisassigned
b
YeDbl=aleinline3ofPIVOT.SincewealwayscallPIVOTwithale0,we
b
como
Yetoequal0,andhencetheobjectivevaluetobeunchanged,wemust
seethatfor b
haveblD0.
Indeed,thissituationcanoccur.Considerthelinearprogram
D x1 Cx2 Cx3
x4 D8 x1 x2
x5 re x2 x3:
Supposethatwechoosex1astheenteringvariableandx4astheleavingvariable.
Afterpivoting,weobtain
D8 Cx3 x4
x1 D8 x2 x4
x5 re x2 x3 :
Atthispoint,ouronlychoiceistopivotwithx3enteringandx5leaving.Desde
b5D0,theobjectivevalueof8remainsunchangedafterpivoting:
D8Cx2 x4 x5
x1 D8 x2 x4
x3 re x2 x5:
Theobjectivevaluehasnotchanged,butourslackformhas.Fortunately,ifwe
pivotagain,withx2enteringandx1leaving,theobjectivevalueincreases(to16),
andthesimplexalgorithmcancontinue.
Degeneracycanpreventthesimplexalgorithmfromterminating,becauseitcan
leadtoaphenomenonknownascycling:theslackformsattwodifferentitera
tionsofSIMPLEXareidentical.Becauseofdegeneracy,SIMPLEXcouldchoosea
sequenceofpivotoperationsthatleavetheobjectivevalueunchangedbutrepeat
aslackformwithinthesequence.SinceSIMPLEXisadeterministicalgorithm,if
itcycles,thenitwillcyclethroughthesameseriesofslackformsforever,never
terminating.
CyclingistheonlyreasonthatSIMPLEXmightnotterminate.Toshowthisfact,
wemustfirstdevelopsomeadditionalmachinery.
Ateachiteration,SIMPLEXmaintainsA,b,c,and inadditiontothesets
NandB.AlthoughweneedtoexplicitlymaintainA,b,c,and inorderto
implementthesimplexalgorithmefficiently,wecangetbywithoutmaintaining
ellos.Inotherwords,thesetsofbasicandnonbasicvariablessufficetouniquely
determinetheslackform.Beforeprovingthisfact,weproveausefulalgebraic
lemma.

https://translate.googleusercontent.com/translate_f 183/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
Page297

876 Chapter29LinearProgramming

Lemma29.3
LetIbeasetofindices.Foreachj2I,letjandjberealnumbers,andletxj
bearealvaluedvariable.Letbeanyrealnumber.Supposethatforanysettings
ofthexj,wehave
x x
jxjDC jxj: (29.78)
j2I j2I
ThenjDjforeachj2I,andD0.

ProofSinceequation(29.78)holdsforanyvaluesofthexj,wecanuseparticular
valuestodrawconclusionsabout,,and.IfweletxjD0foreachj2I,
weconcludethatD0.Nowpickanarbitraryindexj2I,andsetxjD1and
xkD0forallkj.ThenwemusthavejDj.Sincewepickedjasany
indexinI,weconcludethatjDjforeachj2I.

Aparticularlinearprogramhasmanydifferentslackformsrecallthateachslack
formhasthesamesetoffeasibleandoptimalsolutionsastheoriginallinearpro
gramo.Wenowshowthattheslackformofalinearprogramisuniquelydetermined
bythesetofbasicvariables.Thatis,giventhesetofbasicvariables,auniqueslack
form(uniquesetofcoefficientsandrighthandsides)isassociatedwiththosebasic
Variables.

Lemma29.4
Let.Asegundoc/bealinearprograminstandardform.GivenasetBofbasicvariables,
theassociatedslackformisuniquelydetermined.

ProofAssumeforthepurposeofcontradictionthattherearetwodifferentslack
formswiththesamesetBofbasicvariables.Theslackformsmustalsohave
identicalsetsNDf12:::nCmgBofnonbasicvariables.Wewritethefirst
slackformas
x
D do cjxj (29.79)
j2N
x
xi Dbi aijxjfori2B (29.80)
j2N
andthesecondas
x
D 0C cj0xj (29.81)
j2N
x
xi Db0 yo aij
0
xjfori2B:
(29.82)
j2N

Pgina298

29.3Thesimplexalgorithm 877

Considerthesystemofequationsformedbysubtractingeachequationin
line(29.82)fromthecorrespondingequationinline(29.80).Theresultingsys
temis
x
0D.bi b0 .aij a0
i/ ij/xj fori2B
j2N
or,equivalently,
x x
aijxjD.bi b0 a0
i/C ijxj fori2B:
j2N j2N
Now,foreachi2B,applyLemma29.3withjDaij,jDa0 ij,Dbi bi0,and
IDN.SinceiDi,wehavethataijDa0
ijforeachj2N,andsinceD0,
wehavethatbiDb0 i. Thus,forthetwoslackforms,AandbareidenticaltoA0
andb0.Usingasimilarargument,Exercise29.31showsthatitmustalsobethe
casethatcDc0andD0,andhencethattheslackformsmustbeidentical.

WecannowshowthatcyclingistheonlypossiblereasonthatSIMPLEXmight
notterminate.

Lemma29.5
IfSIMPLEXfailstoterminateinatmost nCm iterations,thenitcycles.
metro
ProofByLemma29.4,thesetBofbasicvariablesuniquelydeterminesaslack
formar.TherearenCmvariablesandjBjDm,andtherefore,thereareatmost
nCm waystochooseB.Thus,thereareonlyatmost nCm uniqueslackforms.
metro metro
Therefore,ifSIMPLEXrunsformorethan nCm iterations,itmustcycle.

https://translate.googleusercontent.com/translate_f 184/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
metro
Cyclingistheoreticallypossible,butextremelyrare.Wecanpreventitbychoos
ingtheenteringandleavingvariablessomewhatmorecarefully.Oneoptionisto
perturbtheinputslightlysothatitisimpossibletohavetwosolutionswiththe
sameobjectivevalue.Anotheroptionistobreaktiesbyalwayschoosingthevari
ablewiththesmallestindex,astrategyknownasBland'srule.Weomittheproof
thatthesestrategiesavoidcycling.

Lemma29.6
Iflines4and9ofSIMPLEXalwaysbreaktiesbychoosingthevariablewiththe
smallestindex,thenSIMPLEXmustterminate.

Weconcludethissectionwiththefollowinglemma.

Pgina299

878 Chapter29LinearProgramming

Lemma29.7
AssumingthatINITIALIZESIMPLEXreturnsaslackformforwhichthebasicso
lutionisfeasible,SIMPLEXeitherreportsthatalinearprogramisunbounded,orit
terminateswithafeasiblesolutioninatmost nCm iterations.
metro
ProofLemmas29.2and29.6showthatifINITIALIZESIMPLEXreturnsaslack
formforwhichthebasicsolutionisfeasible,SIMPLEXeitherreportsthatalinear
programisunbounded,oritterminateswithafeasiblesolution.Bythecontra
positiveofLemma29.5,ifSIMPLEXterminateswithafeasiblesolution,thenit
terminatesinatmost nCm iterations.
metro

Exercises

29.31
CompletetheproofofLemma29.4byshowingthatitmustbethecasethatcDc0
andD0.

29.32
ShowthatthecalltoPIVOTinline12ofSIMPLEXneverdecreasesthevalueof.

29.33
ProvethattheslackformgiventothePIVOTprocedureandtheslackformthatthe
procedurereturnsareequivalent.

29.34
Supposeweconvertalinearprogram.Asegundoc/instandardformtoslackform.
Showthatthebasicsolutionisfeasibleifandonlyifbi 0foriD12:::metro.

29.35
SolvethefollowinglinearprogramusingSIMPLEX:
maximize18x1 C12:5x2
sujetoa
x1 do x2 20
x1 12
x2 16
x1x2 0:

Pgina300

29.4Duality 879

29.36
SolvethefollowinglinearprogramusingSIMPLEX:
maximize5x1 3x2
sujetoa
x1 x2 1
2x1 do x2 2

https://translate.googleusercontent.com/translate_f 185/186
13/1/2017 PorqueyesunarazanterioralaLINK,q1.y/D.n/y:rank.LaoperacinLINKdejaycomounaraz,ydejalasy
x1x2 0:

29.37
SolvethefollowinglinearprogramusingSIMPLEX:
minimize x1 do x2 do x3
sujetoa
2x1 C7:5x2 do 3x3 10000
20x1 do 5x2 C10x3 30000
x1x2x3 0:

29.38
IntheproofofLemma29.5,wearguedthatthereareatmost mCn waystochoose
norte
asetBofbasicvariables.Giveanexampleofalinearprograminwhichthereare
strictlyfewerthan mCn waystochoosethesetB.
norte

29.4Duality

Wehaveproventhat,undercertainassumptions,SIMPLEXterminates.Wehavenot
yetshownthatitactuallyfindsanoptimalsolutiontoalinearprogram,however.
Inordertodoso,weintroduceapowerfulconceptcalledlinearprogramming
duality.
Dualityenablesustoprovethatasolutionisindeedoptimal.Wesawanexam
pleofdualityinChapter26withTheorem26.6,themaxflowmincuttheorem.
Supposethat,givenaninstanceofamaximumflowproblem,wefindaflowf
withvaluejfj.Howdoweknowwhetherfisamaximumflow?Bythemaxflow
mincuttheorem,ifwecanfindacutwhosevalueisalsojfj,thenwehavever
ifiedthatfisindeedamaximumflow.Thisrelationshipprovidesanexampleof
duality:givenamaximizationproblem,wedefinearelatedminimizationproblem
suchthatthetwoproblemshavethesameoptimalobjectivevalues.
Givenalinearprograminwhichtheobjectiveistomaximize,weshalldescribe
howtoformulateaduallinearprograminwhichtheobjectiveistominimizeand

https://translate.googleusercontent.com/translate_f 186/186

Você também pode gostar