a. an overview of leda - computer science …valiente/algorithm/leda.pdf · a. an overview of leda...

45
Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag. A. An Overview of LEDA Libraries are great; use them whenever they do the job. Start with your system library, then search other libraries for appropriate functions. —Jon Bentley [31] The detailed exposition of algorithms on trees and graphs made in this book is based on a full C++ implementation of all of the algorithms. These implementations are, in turn, based on the LEDA library of efficient C++ data structures and algorithms. A brief overview of the small subset of LEDA used throughout this book is provided in this appendix, in order to facilitate reading and is aimed at making the book self-contained. The reader is referred to [234, 236] for a more comprehensive description of LEDA. A.1 Introduction LEDA is a library of efficient C++ data structures and algorithms, developed over the last decade at the Max-Plank-Institute f¨ ur Infor- matik in Saarbr¨ ucken, Germany, which is becoming a de facto stan- dard for upper-undergraduate and graduate courses on graph algo- rithms throughout the world. As a matter of fact, LEDA allows the student, lecturer, researcher, and practitioner to complement algorith- mic graph theory with actual implementation and experimentation, building upon a thorough library of efficient implementations of mod- ern data structures and fundamental algorithms. Another widely used library of C++ data structures and algorithms is STL, the ANSI C++ Standard Template Library [243]. STL includes efficient implementations of sequential container (deque, list, stack,

Upload: dominh

Post on 28-Aug-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A. An Overview of LEDA

Librariesaregreat;usethemwhenever they dothe job. Start with your system library, thensearchotherlibrariesfor appropriatefunctions.

—JonBentley [31]

Thedetailedexpositionof algorithmsontreesandgraphsmadein thisbook is basedon a full C++ implementationof all of thealgorithms.Theseimplementationsare, in turn, basedon the LEDA library ofefficient C++ datastructuresandalgorithms.A brief overview of thesmall subsetof LEDA usedthroughoutthis book is provided in thisappendix,in order to facilitate readingand is aimedat making thebook self-contained.The readeris referredto [234, 236] for a morecomprehensivedescriptionof LEDA.

A.1 Intr oduction

LEDA is a library of efficient C++ datastructuresand algorithms,developedover the last decadeat the Max-Plank-Institutefur Infor-matik in Saarbrucken,Germany, which is becominga de factostan-dard for upper-undergraduateand graduatecourseson graphalgo-rithms throughoutthe world. As a matterof fact, LEDA allows thestudent,lecturer, researcher, andpractitionerto complementalgorith-mic graphtheory with actual implementationand experimentation,building uponathoroughlibrary of efficient implementationsof mod-erndatastructuresandfundamentalalgorithms.

Anotherwidely usedlibrary of C++ datastructuresandalgorithmsis STL, theANSI C++ StandardTemplateLibrary [243].STL includesefficient implementationsof sequentialcontainer(deque, list, stack,

Page 2: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

402 A. An Overview of LEDA

vector) andassociativecontainer(map, set) classesaswell asgenericalgorithms,providing a large numberof operationsthat can be ap-plied to theseclassesandto thebuilt-in array classaswell. In muchthesamespirit, BGL, theBoostGraphLibrary [209, 302] that is be-ing consideredfor adoptioninto the ANSI C++ Standard,includesefficient implementationsof severalbasicgraphalgorithmsanddatastructures,designedin thegenericprogrammingstyleof STL.

Whenit comesto combinatorialandgeometriccomputing,though,LEDA goesmuchbeyond STL andBGL by providing efficient im-plementationsof graphsandtheir supportingdatastructures,togetherwith alargenumberof graphalgorithms(includingshortestpath,min-imum spanningtree, bipartite matching,maximumflow, minimumcut,andgraphdrawing algorithms),while still providing efficient im-plementationsof sequentialcontainer(list, queque, stack) andasso-ciative container(dictionary, map, set) classes.Furthermore,LEDAprovides the most efficient datastructuresknown for implementingeachcontainerclass,evenallowing theuserto chooseamongdiffer-ent implementationsfor the sameclass.For instance,the dictionaryclassincludesa default implementationby

2 4 -trees[26], together

with a choiceof several alternative implementationsincluding AVLtrees[1], BB α trees[48, 248], red-blacktrees[143], randomizedsearchtrees[292], andskip lists [262]. Last,but not least,LEDA in-cludesaninterfacefor graphicalinputandoutputin severalplatforms,which facilitatestheeditingandvisualizationof graphsandtheinter-activedemonstrationandanimationof graphalgorithms.

A.2 Data Structures

LEDA consistsof a set of containerclasses,a set of algorithmstooperateover thesecontainerclasses,anda setof iterators to accessthecontentsof acontainer.

Containersare just objectsthat hold other objects.A sequentialcontainer maintainsa first element,a secondelement,and so onthrougha lastelement.Examplesof sequentialcontainersarethe listclass,which providesa linear list; the stack class,which providesastack;andthequeueclass,which providesasingle-endedqueue.

Page 3: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 403

An associativecontainer, on theotherhand,supportsfastlookupof anobjectheldin thecontainer. Examplesof associativecontainersare the dictionary, d array, h array, map, andmap2classes,whichprovide accessto the informationassociatedwith a uniquekey; andthesetclass,whichprovidesaccessto uniqueelements.

Someof the containersprovided by LEDA do not fit, though,inthepreviousdistinctionbetweensequentialandassociativecontainers.Theseincludethe p queueclass,which providesa single-endedpri-ority queue;the two tuple, three tuple, andfour tupleclasses,whichprovide n-tuples of elements;the array and array2 classes,whichprovide one-dimensionaldynamicarraysandtwo-dimensionalstaticarrays,respectively; the sortseqclass,providing sortedsequences,which supportmostof the operationsof the p queueanddictionaryclassestogetherwith further searchoperationsandsomeoperationsof the list class;andthegraphclass,which providesgraphstogetherwith efficient implementationsof mostfundamentalgraphalgorithms.

Furthercontainersprovidedby LEDA includethe integer andra-tional classes,whichprovideanexactrealizationof integerandratio-nalnumbers,respectively, wheretheC++ typesint andlongint arejustan approximationof integer numbers;the bigfloat and real classes,which provide a betterapproximationof real numbersthanthe C++typesfloat, double, and long double; andthe vector, integer vector,matrix, and integer matrix classes,which provide one-dimensionalandtwo-dimensionalarraysof numberstogetherwith basiclinearal-gebraoperations.

Algorithmsoperateon containers,andincludecapabilitiesfor ini-tializing, sorting,searching,andtransformingthecontentof contain-ers. Most LEDA data structuresare implementedas C++ genericclasses,which areparametrizedby thetypeof thecontainer, anden-capsulateinitializing, sorting,searching,andtransformingalgorithms,which arealsoimplementedasC++ genericfunctions,parametrizedagainby the containerelementtype. Most LEDA graphalgorithmsareimplementedasC++ genericfunctionsandwrappedin a separategraph alg class,though,asfurtherdiscussedbelow.

The operationsshown in Fig. A.1 arecommonto the sequentialcontainerclasseslist, stack, andqueue, andtheassociative containerclassesdictionary and set, as well as the containerclassesp queue

Page 4: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

404 A. An Overview of LEDA

andsort seq. Furthermore,the associative containerclassesd arrayandh array provide sizeandclear but no emptyoperation,the mapand map2classesonly provide the clear operation,the array classonly providesthesizeoperation,andthegraphclassprovidesall threeoperations,wherethenumberof nodesoperationgivestheorderandthenumberof edgesoperationgivesthesizeof thegraph.

size() returnsthenumberof elementsin thecontainerempty() returnstrueif thecontaineris emptyandfalseotherwiseclear() makesthecontainerempty

Fig. A.1. Operationscommonto mostLEDA containerclasses.

A.2.1 Linear Lists

The list classprovidesa linear list, that is, a sequenceof elements.The list() constructorcreatesan empty list. Someof the operationsprovidedby the list classareshown in Fig. A.2.

The list classincludesa default implementationby doubly linkedlinearlists.Operationsfront, back, push, append, pop, Pop, conc, size,emptytakeO

1 time; rank, reverse, remove, permute, merge, unique,

clear take On time; bucket sort takesO

n j i time; andsort,

merge sorttakeOnlogn) time,wheren is thesizeor lengthof thelist,

and i and j arethe minimal andmaximalvaluesof a given functionon theelementsof thelist. TherepresentationusesO

n space.

Theefficient implementationof someof theseoperationsrequirestheuseof items, which are,roughly, addressesof containers.Most ofthepreviousoperationshaveacounterpartwhichactsuponlist items.For instance,first and last arethe counterpartof front andback, re-spectively, andreturnthe first andthe last item in the list, assumingthe list is not empty. Furthermore,operationcontents(it) returnstheelementcontainedat item it of thelist.

Iterationover the items or the elementsof a list is implementedby LEDA macros.In a macrocall of the form forall items(it,L), theitemsof list L aresuccessively assignedto item it, andin amacrocallof theform forall(x,L), theelementsof L aresuccessively assignedtovariablex.

Page 5: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 405

front() returnsthe first elementin the list, assumingthe list is notempty

back() returnsthe last elementin the list, assumingthe list is notempty

rank(x) returnsthe rank of elementx in the list, that is, the integerpositionof the first occurrenceof x in the list, or zero is xdoesnotoccurin thelist

push(x) insertselementx at thefront of thelistappend(x) insertselementx at therearof thelistpop() deletesandreturnsthefirst elementin thelist, assumingthe

list is notemptyPop() deletesand returnsthe last elementin the list, assuming

againthatthelist is notemptyremove(x) removesall occurrencesof elementx from thelistconc(L) deletestheelementsof anotherlist L andinsertsthemat the

rearof thelistreverse() reversesthesequenceof elementsof thelistpermute() performsarandompermutationof theelementsof thelistsort() sortsthe list by quick sort usingthe default linearordering

on theelementsmerge sort() sortsthe list by mergesortusingthedefault linearordering

on theelementsbucket sort(f) sortsthelist by bucket sortaccordingto theintegerfunction

f definedon theelementsmerge(L) mergesthelist with L usingthedefault linearorderingonthe

elementsunique() removesduplicateelementsfrom the list, assumingthe list

is alreadysortedaccordingto thedefault linearorderingontheelements

Fig. A.2. Someof theoperationsprovidedby the list class.

A.2.2 Stacks

Thestack classprovidesastack,thatis,asequenceof elementswhichareinsertedanddeletedat thesameend(thetop)of thesequence.Thestack() constructorcreatesan emptystack.The operationsprovidedby thestack classareshown in Fig. A.3.

top() returnsthe top elementin the stack,assumingthe stackisnotempty

pop() deletesandreturnsthetopelementin thestack,assumingthestackis notempty

push(x) insertselementx at thetopof thestack

Fig. A.3. Operationsprovidedby thestack class.

Page 6: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

406 A. An Overview of LEDA

Thestack classincludesadefault implementationby singly linkedlinearlists.Operationstop, pop, push, size, emptytakeO

1 time;and

clear takesOn time, wheren is thesizeof thestack.Therepresen-

tationusesOn space.

A.2.3 Queues

Thequeueclassprovidesa single-endedqueue,thatis, a sequenceofelementswhich are insertedat oneend(the rear)anddeletedat theother end (the front) of the sequence.The queue() constructorcre-atesanemptyqueue.Theoperationsprovidedby thequeueclassareshown in Fig. A.4.

top() returnsthefront elementin thequeue,assumingthequeueisnotempty

pop() deletesandreturnsthefront elementin thequeue,assumingthequeueis notempty

append(x) insertselementx at therearendof thequeue

Fig. A.4. Operationsprovidedby thequeueclass.

Thequeueclassincludesadefault implementationby singlylinkedlinear lists. Operationstop, pop, append, size, emptytake O

1 time;

andclear takesOn time, wheren is thesizeof thequeue.Therep-

resentationusesOn space.

A.2.4 Priority Queues

The p queueclassprovidesa single-endedpriority queue,that is, aqueueof elementswith bothinformationandapriority associatedwitheachelement,wherethereis a linear orderdefinedon the priorities.Thep queue() constructorcreatesanemptypriority queue,basedonthe linear orderdefinedby the global compare function.The opera-tionsprovidedby thep queueclassareshown in Fig. A.5.

Thep queueclassincludesadefault implementationby Fibonacciheaps[119]. Operationsprio, inf, find min, change inf, size, emptytakeO

1 time; insert, decreasep takeamortizedO

1 time;del item,

del min take amortizedOlogn time; and clear takes O

n time,

Page 7: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 407

prio(x) returnsthepriority of elementxinf(x) returnstheinformationassociatedwith elementxinsert(i,p) insertsandreturnsanelementwith informationi andpriority

p in thepriority queuefind min() returnsan elementwith the minimum priority, or nil if the

priority queueis emptydel item(x) deleteselementx from thepriority queuedel min() deletesandreturnsthepriority of anelementwith themini-

mumpriority, assumingthepriority queueis notemptychange inf(x,i) makesi thenew informationassociatedwith elementx in the

priority queuedecreasep(x,p) makes p the new priority of elementx, assumingx already

belongsto the priority queuewith a priority not smallerthanp

Fig. A.5. Operationsprovidedby thep queueclass.

wheren is thesizeof thepriority queue.TherepresentationusesOn

space.Alternative implementationsincludepairing heaps[118, 308], k-

ary andbinary heaps,lists, buckets,redistributive heaps[3], mono-toneheaps,andEmde-Boastrees[335]. The default implementationcanalsobeselectedby theimplementationparameterf heap, andthealternativeimplementationsareselectedby p heap, k heap, bin heap,list pq, b heap, r heap, m heap, andeb tree, respectively.

A.2.5 Tuples

Thetwo tuple, three tuple, andfour tupleclassesproviderespectively2-tuples,3-tuples,and4-tuples.Theoperationsprovidedby the tupleclassesareshown in Fig. A.6.

first() returnsthefirst componentin the2-tuple,3-tuple,or 4-tuplesecond() returnsthe secondcomponentin the 2-tuple,3-tuple,or 4-

tuplethird() returnsthethird componentin the3-tupleor 4-tuplefourth() returnsthefourth componentin the4-tuple

Fig. A.6. Operationsprovidedby thetwo tuple, three tuple, andfour tupleclasses.

The comparisonoperator is definedfor 2-tuples,3-tuples,and4-tuples,togetherwith a compare lexicographiccomparisonoperatorand a Hash hashingfunction. The tuple classesincludean obvious

Page 8: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

408 A. An Overview of LEDA

default implementationby wrappingthe componentsasprivatedatamembersof theclass.Operationsfirst, second, third, andfourth takeO

1 time.TherepresentationusesO

1 spacetimesthetotal sizeof

thecomponents.

A.2.6 Arrays

The array classprovides one-dimensionaldynamicarrays.The ar-ray(a,b) constructorcreatesan array of b a 1 elementsindexedby integers in the range a b ; array(n) createsan array of n ele-mentsindexedby 0 n 1 ; andarray() createsanemptyarrayof el-ements.Someof theoperationsprovidedby thearrayclassareshownin Fig. A.7.

[i] returnsa referenceto elementA i of the array, assumingthata i b

resize(a,b) redefinesthe array to be indexed by integers in the rangea b

low() returnstheminimal index a of thearrayhigh() returnsthemaximalindex b of thearrayinit(x) setsall elementsin thearrayto xswap(i,j) permuteselementsA i andA j in thearraypermute() performsarandompermutationof theelementsof thearraysort() sortsthearrayby quicksortusingthedefault linearordering

on theelementsbinary search(x) returnsthe index i suchthatA i x, or a 1 if elementx

doesnot belongto the array, assumingthe arrayis alreadysortedaccordingto the default linear orderingon the ele-ments

Fig. A.7. Someof theoperationsprovidedby thearray class.

Thearrayclassincludesadefault implementationby C++ vectors.Operations[ ], low, high, swaptake O

1 time; binary search takes

Ologn time; init, permutetake O

n time; andsort takesO

nlogn

time, wheren b a 1. Further, operationresizetakestime linearin the maximumbetweenthe old andthe new sizeof the array. TherepresentationusesO

n spacetimesthesizeof theelements.

Further, the array2 classprovides two-dimensionalstaticarrays.The array2(a,b,c,d) constructorcreatesa two-dimensionalarray ofb a 1 timesd c 1 elementsindexed by integersin the range a b and c d ; andarray2(n,m) createsa two-dimensionalarrayof

Page 9: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 409

n m elementsindexed by 0 n 1 and 0 m 1 . The operationsprovidedby thearray2classareshown in Fig. A.8.

[i,j] returnsa referenceto elementA i j of thearray, assumingthata i b andc j d

low1() returnstheminimal index a of thearrayhigh1() returnsthemaximalindex b of thearraylow2() returnstheminimal index c of thearrayhigh2() returnsthemaximalindex d of thearray

Fig. A.8. Operationsprovidedby thearray2class.

The array2 classincludesa default implementationby C++ vec-tors.Operations[ ], low1, high1, low2, high2takeO

1 time.Therep-

resentationusesOnm spacetimesthe sizeof the elements,where

n b a 1 andm d c 1.

A.2.7 Dictionaries

The dictionary classprovidesan associative container, consistingofa setof elementswith both informationanda uniquekey associatedwith eachelement,wherethereis a linear orderdefinedon the keysandtheinformationassociatedwith anelementis retrievedon theba-sisof its key. Thedictionary() constructorcreatesanemptydictionary,basedonthelinearorderdefinedby theglobalcompare function.Theoperationsprovidedby thedictionaryclassareshown in Fig. A.9.

The dictionary classincludesa default implementationby2 4 -

trees[26]. Operationskey, inf, change inf, empty, sizetakeO1 time;

insert, lookup, access, del, del itemtakeOlogn time;andcleartakes

On time, wheren is the sizeof the dictionary. The representation

usesOn space.

AlternativeimplementationsincludeAVL trees[1], BB α trees[48,248], red-blacktrees[143], randomizedsearchtrees[292], andskiplists [262].Thedefault implementationcanalsobeselectedby theim-plementationparameterab tree, andthe alternative implementationsareselectedby avl tree, bb tree, rb tree, rs tree, andskiplist, respec-tively.

Page 10: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

410 A. An Overview of LEDA

key(x) returnsthekey associatedwith elementxinf(x) returnstheinformationassociatedwith elementx[x] returnsa referenceto the information associatedwith ele-

mentxinsert(k,i) insertsandreturnsanelementwith key k andinformation i

in thedictionary, replacingtheelement(if any) with key klookup(k) returnstheelementwith key k in thedictionary, or nil if there

is nosuchelementaccess(k) returnsthe informationassociatedwith key k in the dictio-

nary, assumingthereis suchanelementdel(k) deletestheelementwith key k from thedictionary, if thereis

suchanelementdel item(x) deleteselementx from thedictionary, assumingx belongsto

thedictionarychange inf(x,i) makesi theinformationassociatedwith elementx, assuming

x belongsto thedictionary

Fig. A.9. Operationsprovidedby thedictionaryclass.

A.2.8 Dictionary Arrays

Thed arrayclassprovidesasecondkind of associativecontainer, alsoconsistingof asetof elementswith bothinformationandauniquekeyassociatedwith eachelement,wherethereis a linearorderdefinedonthekeys.Thed array() constructorcreatesanemptydictionaryarray.Theoperationsprovidedby thed arrayclassareshown in Fig. A.10.

[k] returnsa referenceto the informationassociatedwith key kin thedictionaryarray

[k]=i insertsan elementwith key k andinformation i in the dic-tionaryarray, replacingtheelement(if any) with key k, andreturnsareferenceto theinformationassociatedwith theel-ement

defined(k) returnstrueif thereis anelementwith key k in thedictionaryarrayandfalseotherwise

undefine(k) deletestheelementwith key k from thedictionaryarrayandleaveskey k undefined

Fig. A.10. Operationsprovidedby thed array class.

The d array classincludesa default implementationby random-ized searchtrees[292]. OperationsizetakesO

1 time; [ ], defined,

undefinetakeOlogn time;andclear takesO

n time,wheren is the

sizeof thedomain.TherepresentationusesOn space.

Alternative implementationsinclude2 4 -trees[26], AVL trees

[1], BB α trees[48, 248], unbalancedbinary trees,red-blacktrees

Page 11: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 411

[143], and skip lists [262]. The default implementationcanalso beselectedby the implementationparameterrs tree, andthealternativeimplementationsare selectedby ab tree, avl tree, bb tree, bin tree,rb tree, andskiplist, respectively.

Iterationover definedelementsis implementedby LEDA macros.In a macrocall of the form forall defined(k,A), the keys associatedwith theelementsin thedictionaryarrayaresuccessively assignedtovariablek, andin a macrocall of theform forall(i,A), theinformationassociatedwith theelementsof thedictionaryarrayaresuccessivelyassignedto variablei.

A.2.9 Hashing Arrays

Theh array classprovidesa third kind of associativecontainer, con-sisting of a set of elementswith both an information and a uniquekey associatedwith eachelement,wherethereis a hashingfunctiondefinedonthekeys.Theh array() constructorcreatesanemptyhash-ing array. Theoperationsprovidedby theh array classareshown inFig. A.11.

[k] returnsa referenceto the informationassociatedwith key kin thehashingarray

[k]=i insertsanelementwith key k andinformationi in thehashingarray, replacingtheelement(if any) with key k, andreturnsa referenceto theinformationassociatedwith theelement

defined(k) returnstrue if thereis anelementwith key k in thehashingarrayandfalseotherwise

undefine(k) deletesthe elementwith key k from the hashingarrayandleaveskey k undefined

Fig. A.11. Operationsprovidedby theh array class.

The h array classincludesa default implementationby hashingwith chaining.OperationsizetakesO

1 time; [ ], defined, undefine

take expectedO1 time; andclear takesO

n time, wheren is the

sizeof thehashingarray. TherepresentationusesOn space.

Thereis an alternative implementationby dynamicperfecthash-ing [93, 117].Thedefault implementationcanalsobeselectedby theimplementationparameterch hash, and the alternative implementa-tion is selectedby dp hash.

Page 12: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

412 A. An Overview of LEDA

Again, iterationover definedelementsis implementedby LEDAmacros.In amacrocall of theform forall defined(k,A), thekeysasso-ciatedwith theelementsin thehashingarrayaresuccessivelyassignedto variablek, andin a macrocall of theform forall(i,A), theinforma-tion associatedwith theelementsof thehashingarrayaresuccessivelyassignedto variablei.

A.2.10 Maps

The map classprovides still a fourth kind of associative container,consistingof asetof elementswith bothinformationandauniquekeyassociatedwith eachelement,wherekeys areeitherof thetype int orof apointeror itemtype.Themap() constructorcreatesanemptymap.Theoperationsprovidedby themapclassareshown in Fig. A.12.

[k] returnsa referenceto the informationassociatedwith key kin themap

[k]=i insertsanelementwith key k andinformation i in themap,replacingtheelement(if any) with key k, andreturnsa ref-erenceto theinformationassociatedwith theelement

defined(k) returnstrueif thereis anelementwith key k in themapandfalseotherwise

Fig. A.12. Operationsprovidedby themapclass.

Themapclassincludesa default implementationby hashingwithchaining and table doubling. Operations[ ], definedtake expectedO

1 time; andclear takesO

n time, wheren is the numberof el-

ementsin themap.TherepresentationusesOn space.

IterationoverdefinedelementsisalsoimplementedbyLEDA mac-ros.In amacrocall of theform forall defined(k,A), thekeysassociatedwith theelementsin themaparesuccessively assignedto variablek,andin amacrocall of theform forall(i,A), theinformationassociatedwith theelementsof themaparesuccessively assignedto variablei.

Further, themap2classprovidesanassociative containerconsist-ing of a setof elementswith both informationanda uniqueorderedpair of keys associatedwith eachelement.The map2() constructorcreatesan emptytwo-dimensionalmap.The operationsprovided bythemap2classareshown in Fig. A.13.

Page 13: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 413

(k,l) returnsa referenceto the information associatedwith keypair k l in thetwo-dimensionalmap

(k,l)=i insertsan elementwith key pair k l andinformation i inthetwo-dimensionalmap,replacingtheelement(if any) withkey pair k l , andreturnsa referenceto theinformationas-sociatedwith theelement

defined(k,l) returnstrue if thereis an elementwith key pair k l in thetwo-dimensionalmapandfalseotherwise

Fig. A.13. Operationsprovidedby themap2class.

Themap2classincludesadefault implementationby hashingwithchaining and table doubling. Operations( ), definedtake expectedO

1 time; andclear takesO

n time, wheren is the numberof el-

ementsin the two-dimensionalmap. The representationusesOn

space.

A.2.11 Sets

Thesetclassprovidesa setof elements.Theset() constructorcreatesan emptyset.The operationsprovided by the setclassareshown inFig. A.14.

insert(x) insertselementx in thesetdel(x) deleteselementx from thesetmember(x) returnstrueif x belongsto thesetandfalseotherwisechoose() returnssomeelementof the set, assumingthe set is not

emptyjoin(T) returnstheunionof thesetwith setTdiff(T) returnsthedifferenceof thesetminussetTintersect(T) returnstheintersectionof thesetwith setTsymdiff(T) returnsthesymmetricdifferenceof thesetandsetT

Fig. A.14. Operationsprovidedby thesetclass.

The comparisonoperators , , , , , and aredefinedforthe set class.The set class is implementedby randomizedsearchtrees[292].Operationsempty, size, choosetakeO

1 time; insert, del,

membertakeexpectedOlogn time; clear takesO

n time; andjoin,

diff, intersect, symdiff take expectedOnlogn time, wheren is the

sizeof theset.

Page 14: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

414 A. An Overview of LEDA

Iterationover theelementsof a setis alsoimplementedby LEDAmacros.In a macrocall of the form forall(x,S), theelementsof setSaresuccessively assignedto variablex.

A.2.12 Partitions

The partition classprovides a partition of a finite set of items intodisjoint subsets,calledblocks. The partition() constructorcreatesanemptypartitionof anemptysetof elements.Theoperationsprovidedby thepartition classareshown in Fig. A.15.

make block() returnsa new item andinsertsa singletonblock containingtheitem in thepartition

find(p) returnsacanonicalrepresentative itemof theblockthatcon-tainsitem p

size(p) returnsthesizeof theblock containingitem pnumberof blocks() returnsthenumberof blocksin thepartitionsameblock(p,q) returnstrueif itemsp andq belongto thesameblock of the

partitionandfalseotherwiseunion blocks(p,q) combinestheblocksof thepartitioncontainingitems p and

qsplit(L) splits all blockscontainingitemsin a list of itemsL of the

partitioninto singletonblocks

Fig. A.15. Operationsprovidedby thepartition class.

Thepartition classincludesadefault implementationby theunion-find datastructurewith weightedunion andpathcompression[318,321]. Operationnumberof blocks takes O

1 time; a sequenceof

n operationsmake block and a total of m n operationsfind, size,sameblock, union blockstakesO

m n time,wherethevalueof

αm n , theinverseAckermannfunction,is lessthanor equalto 4 for

all practicalpurposes;andoperationsplit takestime linearin thesizeof theblocks.TherepresentationusesO

n space,wheren is now the

sizeof theset.

A.2.13 SortedSequences

Thesortseqclassprovidesasortedsequence,thatis, asequenceof el-ementswith both informationanda uniquekey associatedwith each

Page 15: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 415

element,wherethereis a linear orderdefinedon thekeys. The sort-seq() constructorcreatesanemptysortedsequence,basedon the lin-earorderdefinedby theglobalcompare function.Someof theopera-tionsprovidedby thesortseqclassareshown in Fig. A.16.

key(it) returnsthekey associatedwith item itinf(it) returnstheinformationassociatedwith item itinsert(k,i) insertsandreturnsanelementwith key k andinformation i

in the sortedsequence,replacingthe element(if any) withkey k

lookup(k) returnstheelementwith key k in thesortedsequence,or nilif thereis nosuchelement

del(k) deletestheelementwith key k from the sortedsequence,ifthereis suchanelement

del item(it) deletesitem it from thesortedsequence,assumingit belongsto thesequence

change inf(it,i) makes i theinformationassociatedwith item it, assumingitbelongsto thesortedsequence

Fig. A.16. Someof theoperationsprovidedby thesortseqclass.

Sortedsequencesalsooffer so-calledfinger searchoperations,aswell as operationsfor splitting and merging sortedsequences.Thesortseqclassincludesa default implementationby skip lists [262].Operationsempty, size, key, inf, del item, change inf take O

1 time;

insert, lookup, del take expectedOlogn time; andclear takesO

n

time, wheren is the sizeof the sortedsequence.The representationusesO

n spacetimesthesizeof theelements.

Alternative implementationsof sortedsequencesinclude2 4 -

trees[26], BB α trees[48, 248], red-blacktrees[143], andrandom-ized searchtrees[292]. The default implementationcanalsobe se-lectedby the implementationparameterskiplist, and the alternativeimplementationsareselectedby ab tree, bb tree, rb tree, andrs tree,respectively.

A.2.14 Graphs

Thegraphclassprovidesdirectedgraphs,andalsoundirectedgraphsrepresentedby bidirectedgraphs.Thegraph() constructorcreatesanemptygraph.Someof theoperationsprovidedby thegraphclassareshown in Fig. A.17.

Page 16: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

416 A. An Overview of LEDA

outdeg(v) returnsthenumberof arcsgoingoutof vertex vindeg(v) returnsthenumberof arcscominginto vertex vsource(e) returnsthesourcevertex of arcetarget(e) returnsthetargetvertex of arceopposite(v,e) returns target(e) if vertex v is the source of arc e and

source(e) otherwisenumberof nodes() returnstheorderof thegraphnumberof edges() returnsthesizeof thegraphchoosenode() returnsa vertex of thegraphat random,or nil if thegraphis

emptychooseedge() returnsan arcof the graphat random,or nil if the graphis

emptyall nodes() returnsa list of all theverticesof thegraphall edges() returnsa list of all thearcsof thegraphadj edges(v) returnsa list of all thearcsgoingout of vertex vin edges(v) returnsa list of all thearcscominginto vertex vadj nodes(v) returnsa list of all theverticesadjacentto vertex vnew node() insertsandreturnsa vertex in thegraphnew edge(v,w) insertsandreturnsanarc in thegraphgoingout of vertex v

andcominginto vertex wdel node(v) deletesvertex v from thegraph,togetherwith all thosearcs

goingoutof or cominginto vertex vdel edge(e) deletesarce from thegraphdel all nodes() deletesall verticesfrom thegraphdel all edges() deletesall arcsfrom thegraphsort nodes(cmp) sortsthegraphby quicksortaccordingto thelinearordering

cmpdefinedon theverticesbucket sort nodes(f) sortsthegraphby bucket sortaccordingto theinteger func-

tion f definedon theverticessort edges(cmp) sortsthegraphby quicksortaccordingto thelinearordering

cmpdefinedon thearcsbucket sort edges(f) sortsthegraphby bucket sortaccordingto theinteger func-

tion f definedon thearcsempty() returnstrueif thegraphis emptyandfalseotherwiseclear() makesthegraphempty

Fig. A.17. Someof theoperationsprovidedby thegraphclass.

The graph class includes a default implementationby doublylinked lists of verticesand arcs.Operationsoutdeg, indeg, source,target, opposite, numberof nodes, numberof edges, choosenode,chooseedge, new node, new edge, del node, del edge, empty takeO

1 time; adj edges, adj nodestake time linear in theoutdegreeof

the vertex; in edges takes time linear in the indegreeof the vertex;all nodes, all edges, del all nodes, del all edges, bucket sort nodes,bucket sort edges, clear take O

n m time; operationsort nodes

takes Onlogn time; and sort edges takes O

mlogm time, where

Page 17: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 417

n is theorderandm is thesizeof thegraph.TherepresentationusesO

n m space.Therearefurtheroperationssupportingiterationover thevertices

andarcsof a graph.An alternative form of iterationis implementedby LEDA macros.In a macro call of the form forall nodes(v,G),the verticesof graphG aresuccessively assignedto variablev; in amacrocall forall edges(e,G), thearcsof graphG aresuccessively as-signedto variablee; in a macrocall forall rev nodes(v,G), the ver-tices of graphG are successively assignedto variablev in reverseorder; in a macrocall forall rev edges(e,G), the arcsof graphG aresuccessively assignedto variablee in reverseorder; in a macrocallforall out edges(e,v), the arcsgoing out of vertex v aresuccessivelyassignedto variablee; in a macrocall forall in edges(e,w), the arcscominginto vertex w aresuccessively assignedto variablee; andin amacrocall of theform forall adj nodes(w,v), theverticesadjacenttovertex v aresuccessively assignedto variablew.

Informationcanbeassociatedwith theverticesandarcsof agraphby definingappropriatearrays,matrices,or mapsof verticesandarcs.While theformerarestaticdatastructures,valid only for theverticesandarcscontainedin thegraphat themomentof creationof thearrayor matrix, thelatteraredynamicdatastructures,which arealsovalidfor verticesandarcsinsertedlaterin thegraph.

Thenodearrayclassprovidesastaticarrayof informationassoci-atedwith theverticesof agraph.Thenodearray() constructorcreatesanemptystaticarrayof informationto beassociatedwith theverticesof a graph,thenodearray(G) constructorcreatesa staticarrayof in-formationindexedby theverticesof graphG, andthenodearray(G,x)constructorcreatesa staticarrayof information indexed by the ver-ticesof graphG andinitializes all entriesto the valueof variablex.Someof theoperationsprovidedby thenodearrayclassareshown inFig. A.18.

The nodearray classincludesa default implementationby C++vectorsandaninternalnumberingof theverticesof thegraph.Oper-ationsget graph, [ ] take O

1 time; and init takesO

n time, where

n is theorderof thegraph.TherepresentationusesOn spacetimes

thesizeof theinformationassociatedwith thevertices.

Page 18: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

418 A. An Overview of LEDA

get graph() returnsareferenceto thegraphwhichthearrayof verticesisassociatedwith

[v] returnsa referenceto theinformationassociatedwith vertexv

init(G) makesthearrayvalid for all verticesof graphGinit(G,x) makesthearrayvalid for all verticesof graphG andinitial-

izesall entriesto thevalueof variablex

Fig. A.18. Someof theoperationsprovidedby thenodearrayclass.

Theedge arrayclassprovidesastaticarrayof informationassoci-atedwith thearcsof a graph.Theedge array() constructorcreatesanemptystaticarrayof informationto be associatedwith the arcsof agraph,theedge array(G) constructorcreatesastaticarrayof informa-tion indexedby thearcsof graphG, andtheedge array(G,x) construc-tor createsa staticarrayof informationindexedby thearcsof graphG and initializes all entriesto the valueof variablex. Someof theoperationsprovidedby theedge arrayclassareshown in Fig. A.19.

get graph() returnsa referenceto the graphwhich the array of arcsisassociatedwith

[e] returnsa referenceto theinformationassociatedwith arceinit(G) makesthearrayvalid for all arcsof graphGinit(G,x) makesthearrayvalid for all arcsof graphG andinitializes

all entriesto thevalueof variablex

Fig. A.19. Someof theoperationsprovidedby theedge arrayclass.

The edge array classincludesa default implementationby C++vectorsandaninternalnumberingof thearcsof thegraph.Operationsget graph, [ ] takeO

1 time;andinit takesO

m time,wherem is the

sizethegraph.TherepresentationusesOm spacetimesthesizeof

theinformationassociatedwith thearcs.The nodematrix classprovidesa statictwo-dimensionalarrayof

informationassociatedwith theverticesof agraph.Thenodematrix()constructorcreatesanemptystatictwo-dimensionalarrayof informa-tion to beassociatedwith theverticesof a graph,thenodematrix(G)constructorcreatesa statictwo-dimensionalarrayof informationin-dexedby theverticesof graphG, andthenodematrix(G,x) construc-tor createsa statictwo-dimensionalarrayof informationindexedbytheverticesof graphG andinitializesall entriesto thevalueof vari-

Page 19: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 419

ablex. Someof theoperationsprovidedby thenodematrix classareshown in Fig. A.20.

get graph() returnsa referenceto thegraphwhich the two-dimensionalarrayof verticesis associatedwith

[v] returnsa referenceto thenodearray associatedwith vertexv

(v,w) returnsa referenceto the informationassociatedwith ver-ticesv andw

init(G) makesthetwo-dimensionalarrayvalid for all vertex pairsofgraphG

init(G,x) makesthetwo-dimensionalarrayvalid for all vertex pairsofgraphG andinitializesall entriesto thevalueof variablex

Fig. A.20. Someof theoperationsprovidedby thenodematrixclass.

Thenodematrixclassincludesadefault implementationby nodearray vectorsandan internalnumberingof theverticesof thegraph.Operationsget graph, [ ], ( ) takeO

1 time;andinit takesO

n2 time,

wheren is theorderof thegraph.TherepresentationusesOn2 space

timesthesizeof theinformationassociatedwith thevertices.The nodemapandedge mapclassesprovidesdynamicarraysof

informationassociatedwith the verticesandthe arcsof a graph,re-spectively. Thenodemap() andedge map() constructorscreateemptydynamicarraysof informationto beassociatedwith theverticesandarcsof a graph,thenodemap(G) andedge map(G) constructorscre-ate dynamicarraysof information indexed by the verticesandarcsof graphG, andthe nodemap(G,x) andedge map(G,x) constructorscreatedynamicarraysof informationindexedby theverticesandarcsof graphG andinitialize all entriesto the valueof variablex. Someof theoperationsprovidedby thenodemapandedge mapclassesareshown in Fig. A.21.

Thenodemapandedge mapclassesincludesadefault implemen-tationby hashingbasedon an internalnumberingof theverticesandarcsof the graph.Operationsget graph, init take O

1 time; and[ ]

takes expectedO1 time. The representationusesO

n and O

m

spacetimes the sizeof the informationassociatedwith the verticesandarcs,respectively, wheren is the orderandm is the sizeof thegraph.

Page 20: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

420 A. An Overview of LEDA

get graph() returnsa referenceto thegraphwhich thedynamicarrayisassociatedwith

[v] returnsa referenceto theinformationassociatedwith vertexv

[e] returnsa referenceto theinformationassociatedwith arceinit(G) makes the dynamic array valid for all verticesor arcs of

graphGinit(G,x) makes the dynamic array valid for all verticesor arcs of

graphG and initializes all entriesto the value of variablex

Fig. A.21. Someof theoperationsprovidedby thenodemapandedge mapclasses.

Thenodemap2classprovidesadynamictwo-dimensionalarrayofinformationassociatedwith theverticesof agraph.Thenodemap2()constructorcreatesan emptydynamictwo-dimensionalarray of in-formation to be associatedwith the verticesof a graph,constructornodemap2(G) createsa dynamictwo-dimensionalarrayof informa-tion indexedby theverticesof graphG, andthenodemap2(G,x) con-structorcreatesa dynamictwo-dimensionalarrayof informationin-dexedby theverticesof graphG andinitializesall entriesto thevalueof variablex. Someof theoperationsprovidedby thenodemap2classareshown in Fig. A.22.

get graph() returnsa referenceto thegraphwhich the two-dimensionalarrayof verticesis associatedwith

(v,w) returnsa referenceto the informationassociatedwith ver-ticesv andw

defined(v,w) returnstrueif thereis anentryin thetwo-dimensionalarrayfor verticesv andw andfalseotherwise

init(G) makesthetwo-dimensionalarrayvalid for all vertex pairsofgraphG

init(G,x) makesthetwo-dimensionalarrayvalid for all vertex pairsofgraphG andinitializesall entriesto thevalueof variablex

Fig. A.22. Someof theoperationsprovidedby thenodemap2class.

The nodemap2classincludesa default implementationby hash-ing basedon an internalnumberingof theverticesof thegraph.Op-erationsget graph, init take O

1 time; and( ), definedtake expected

O1 time. TherepresentationusesO

n m spacetimesthesizeof

theinformationassociatedwith thevertices,wheren is theorderandm is thesizeof thegraph.

Page 21: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 421

An alternative form of associatinginformationwith verticesandarcs consistsof using graphsparametrizedby the type of the in-formation associatedwith the verticesand arcs of the graph.TheGRAPHclassprovidesparametrizeddirectedgraphs,andalsoundi-rectedgraphsrepresentedby bidirectedgraphs.The GRAPH(V,E)constructorcreatesan emptygraphparametrizedby vertex informa-tion typeV andarc informationtypeE. TheGRAPHclassis derivedfrom the graph class,and inheritsall of the operationsprovided bythegraphclass.Furtheroperationsprovidedby theGRAPHclassareshown in Fig. A.23.

inf(v) returnstheinformationassociatedwith vertex v[v] returnsa referenceto theinformationassociatedwith vertex

vinf(e) returnstheinformationassociatedwith arce[e] returnsa referenceto theinformationassociatedwith arcenodedata() makes the information associatedwith the verticesof the

graphavailableasa nodearrayedge data() makestheinformationassociatedwith thearcsof thegraph

availableasanedge arrayassign(v,x) makesx theinformationassociatedwith vertex vassign(e,x) makesx theinformationassociatedwith arcenew node(x) insertsandreturnsa vertex in the graphwith informationx

associatednew edge(v,w,x) insertsandreturnsanarc in thegraphgoingout of vertex v

andcominginto vertex w with informationx associated

Fig. A.23. Someof theadditionaloperationsprovidedby theGRAPHclass.

The GRAPHclassincludesa default implementationby doublylinked lists of verticesandarcs.Operationsinf, [ ], nodedata, edgedata, assign, new node, new edge takeO

1 time.Therepresentation

usesOn spacetimesthesizeof theinformationassociatedwith the

verticesplusOm spacetimesthesizeof theinformationassociated

with thearcs,wheren is theorderandm is thesizeof thegraph.LEDA alsoprovideslinear lists, priority queues,andpartitionsof

thesetof verticesof a graph,which have a moreefficient implemen-tationthanthecorrespondinggenericclasses.Thenodelist classpro-videsalinearlist of theverticesof agraphthatcancontaineachvertexof thegraphatmostonce,with theadditionalrestrictionthateachver-tex of a graphis containedin at mostonelinear list of vertices.The

Page 22: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

422 A. An Overview of LEDA

nodelist() constructorcreatesan emptylist of vertices.Someof theoperationsprovidedby thenodelist classareshown in Fig. A.24.

Thenodelist classincludesa default implementationby a doublylinkedlist of vertices,togetherwith a mapof verticesindexedby theverticesof thegraph.Operationsappend, push, insert, pop, del, head,tail, succ, pred, emptytake O

1 time; membertakesexpectedO

1

time; andclear takesOn time, wheren is the sizeor lengthof the

linearlist of vertices.Iterationover theverticesin a linear list of verticesis alsoimple-

mentedby LEDA macros.In a macrocall of theform forall(x,L), theverticesof L aresuccessively assignedto variablex.

append(v) appendsvertex v to thelist of verticespush(v) insertsvertex v at thefront of thelist of verticesinsert(v,w) insertsvertex v right aftervertex w, assumingw belongsto

thelistpop() deletesandreturnsthefirst vertex from thelist, assumingthe

list of verticesis notemptydel(v) deletesvertex v from the list of vertices,assumingthereis

sucha vertexmember(v) returnstrueif vertex v belongsto thelist of verticesandfalse

otherwisehead() returnsthefirst vertex in thelist of vertices,or nil if the list

is emptytail() returnsthe lastvertex in the list of vertices,or nil if the list

is emptysucc(v) returnsthe successorof vertex v in the list of vertices,as-

sumingthelist is not emptypred(v) returnsthepredecessorof vertex v in the list of vertices,as-

sumingthelist is not emptyempty() returnstrueif thelist of verticesis emptyandfalseotherwiseclear() makesthelist of verticesempty

Fig. A.24. Someof theoperationsprovidedby thenodelist class.

The nodepq classprovidesa priority queueof the verticesof agraphthatcancontaineachvertex of thegraphatmostonce,with theadditionalrestrictionthatonly onepriority queueof verticesmaybeusedfor agraph.Thenodepq(G) constructorcreatesapriority queueof the verticesof graphG. The operationsprovided by the nodepqclassareshown in Fig. A.25.

The nodepq classincludesa default implementationby priorityqueues—implemented,in turn, by binary heaps—andarraysof ver-

Page 23: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.2 DataStructures 423

tices.Operationsprio, inf, member, find min, size, emptytake O1

time; insert, del, del min, decreasep take Ologm time; andclear

takesOm time,wherem is thesizeof thepriority queue.Therepre-

sentationusesOn space,wheren is theorderof thegraph.

The nodepartition classprovidesa partition of the verticesof agraph.Thenodepartition(G) constructorcreatesa trivial partitionoftheverticesof graphG, containinga singletonblock for eachvertexof thegraph.Theoperationsprovidedby thenodepartition classareshown in Fig. A.26.

prio(v) returnsthepriority of vertex vinf(v) returnstheinformationassociatedwith vertex vmember(v) returnstrueif vertex v belongsto thepriority queueandfalse

otherwiseinsert(v,p) insertsvertex v with priority p in thepriority queuefind min() returnsa vertex with theminimumpriority, or nil if thepri-

ority queueis emptydel(v) deletesvertex v from thepriority queuedel min() deletesandreturnsa vertex with the minimum priority, as-

sumingthepriority queueis not emptydecreasep(v,p) makes p the new priority of vertex v, assumingv already

belongsto thepriority queuewith apriority notsmallerthanp

Fig. A.25. Operationsprovidedby thenodepq class.

find(v) returnsa canonicalrepresentative vertex of the block con-tainingvertex v

size(v) returnsthesizeof theblock containingvertex vsameblock(v,w) returnstrue if verticesv andw belongto thesameblock of

thepartitionandfalseotherwiseunion blocks(v,w) combinesthe blocks of the partition containingverticesv

andwsplit(L) splitsall blockscontainingverticesin a list of verticesL of

thepartitioninto singletonblocksmake rep(v) makesvertex v thecanonicalrepresentativeof theblockcon-

tainingit

Fig. A.26. Operationsprovidedby thenodepartition class.

The nodepartition classincludesa default implementationby apartition—implementedin turn by theunion-finddatastructurewithweightedunionandpathcompression—togetherwith astaticarrayofitemsof thepartition indexedby theverticesof thegraph.Initializa-tion takesO

n time; operationsfind, size, sameblock, union blocks,

Page 24: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

424 A. An Overview of LEDA

make rep take amortizedOα

n time, wheren is the orderof the

graphandthevalueof αn , the inverseAckermannfunction, is less

thanor equalto 4 for all practicalpurposes;andsplit takestime linearin thesizeof theblocks.TherepresentationusesO

n space.

Further data structuresprovided by LEDA include compressedBooleanarrays;strings;randombits, characters,andnumbers;datastructuresfor graphicalinput andoutput;andcomputationalgeome-try datastructures.Thereaderis referredto [236] for details.

BFS(G,s,dist)computesthedistancedist in graphG of all verticesreachablefrom vertex sduringa breadth-firsttraversalof thegraphin O n m time [232] [235, Sect.7.3], andreturnsa list of all visitedvertices

BICONNECTEDCOMPONENTS(G,compnum)computesthebiconnectedcomponentsof anundirectedgraphG in O n m time[74] andreturnsthe numberof biconnectedcomponents,togetherwith thecom-ponentnumbercompnumto whicheachedgebelongs

COMPONENTS(G,compnum)computestheconnectedcomponentsof anundirectedgraphG in O n m time[232] andreturnsthenumberof connectedcomponents,togetherwith thecompo-nentnumbercompnumto which eachedgebelongs

DFS NUM(G,dfsnum,compnum)computesthenumberdfsnumandcompnumin which theverticesarefirst andlastvisited, respectively, during a depth-firsttraversalof graphG in O n m time[235, Sect.7.3] [317] andreturnsa list of treeedgesin thecorrespondingdepth-first forestof thegraph

STRONG COMPONENTScomputesthe strong componentsof graph G in O n m time [232] [235,Sect.7.4.2]andreturnsthenumberof strongcomponents,togetherwith thestrongcomponentnumbercompnumto whicheachvertex belongs

TOPSORT(G,ord)computesa topologicalsortord of anacyclic graphG in O n m time [176] andreturnstrueif thegraphis indeedacyclic andfalseotherwise

TRANSITIVECLOSURE(G)computesthetransitive closureof graphG in O n m time [134]

Fig. A.27. Somebasicgraphalgorithmsprovidedby LEDA.

A.3 FundamentalGraph Algorithms

LEDA providesefficient implementationsof a largenumberof graphalgorithms,includingtraversal,connectivity, shortestpath,minimumspanningtree,bipartitematching,maximumflow, minimumcut,algo-rithmsfor planargraphs,andgraphdrawing algorithms.Thesegraph

Page 25: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.3 FundamentalGraphAlgorithms 425

algorithmsareimplementedasC++ genericfunctions,andacceptbothgraphsandparametrizedgraphsasarguments.

Basic graph algorithmsprovided by LEDA include topologicalsorting;depth-firstandbreadth-firsttraversal;connected,biconnected,andstronglyconnectedcomponents;andtransitiveclosurealgorithms.Someof themaresummarizedin Fig. A.27.

FurthergraphalgorithmsprovidedbyLEDA includeseveralsingle-sourceshortestpathandall-pairsshortestpathsalgorithms,aswell asminimumspanningtreealgorithms.Someof themaresummarizedinFig. A.28.

ACYCLICSHORTESTPATH(G,s,cost,dist,pred)computesthedistancedist andtheshortestpatharcspred in anacyclic graphGwith arccostscostof all verticesreachablefrom vertex s in O n m time [235,Sect.7.5.4]

ALL PAIRSSHORTESTPATHS(G,cost,dist)computesthedistancedist betweenall reachablepairsof verticesin graphG withno negative-costcycles in O nm n2 logn time [235, Sect.7.5.10]andreturnstrueif thegraphhasindeedno negative-costcyclesandfalseotherwise

BELLMANFORD(G,s,cost,dist,pred)computesthedistancedistandtheshortestpatharcspredin graphG with arccostscostof all verticesreachablefrom vertex s in O nm time [29] [235, Sect.7.5.7–7.5.9] andreturnsfalseif thereis a negative-costcycle reachablefrom s in thegraphandtrueotherwise

DIJKSTRA(G,s,cost,dist,pred)computesthedistancedistandtheshortestpatharcspred in graphG with nonneg-ative arccostscostof all verticesreachablefrom vertex s in O m nlogn time[94] [235, Sect.6.6]

MIN SPANNING TREE(G,cost)computesa spanningtreeof minimum costof an undirectedgraphG with edgecostscostin O n m time [204] [235, Sect.6.8] andreturnsa list of theedgesintheminimumspanningtree

SPANNING TREE(G)computesa spanningtreeof an undirectedgraphG in O n m time [232] andreturnsa list of theedgesin thespanningtree

Fig. A.28.Furthergraphalgorithmsfor shortestpathsandminimumspanningtreesprovidedby LEDA.

Additional graphalgorithmsprovided by LEDA include severalmatchingalgorithmsin bipartiteandgeneralgraphs,aswell ascom-binatorialoptimizationalgorithmsfor computingamaximumor min-imum flow in anetwork, andminimumcutalgorithms.Someof themaresummarizedin Fig. A.29.

Page 26: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

426 A. An Overview of LEDA

MAX CARDBIPARTITEMATCHING(G)computesa matchingof maximumcardinalityin a bipartitegraphG in O nmtime [7, 165] or in O nm time [114], andreturnsthelist of edgesin thematching

MAX CARDMATCHING(G)computesa matching of maximum cardinality in an undirectedgraph G inO nmα n m time [103, 121], andreturnsthelist of edgesin thematching

MAX FLOW(G,s,t,cap)computesamaximum s t -flow in anetwork G s t cap with arccapacitiescapin O n2 m time [128] [235, Sect.7.10]andreturnsthevalueof theflow

MAX WEIGHTASSIGNMENT(G,cost,pot)computesaperfectmatchingof maximumcostin anundirectedgraphG with edgecostscostin O n m nlogn! time[235, Sect.7.8] andreturnsthelist of edgesinthematchinganda correctnesscertificatepot

MAX WEIGHTBIPARTITEMATCHING(G,cost,pot)computesa matchingof maximumcost in a bipartite graphG with edgecostscost in O n m nlogn! time [235, Sect.7.8] andreturnsthelist of edgesin thematching,togetherwith acorrectnesscertificatepot

MIN CUT(G,weight)computesacutof minimumweightin graphG with arcweightsweightin O nmn2 logn time [11, 310] andreturnsthevalueof thecut

Fig. A.29. Furthergraphalgorithmsfor flows in networksandcutsandmatchingsin graphsprovidedby LEDA.

Beware that the maximum cardinality bipartite matchingalgo-rithmsactuallytransformthe representationof thegraphby reorder-ing adjacency lists, therebymodifying the combinatorialembeddingof thegraph.Bewarealsothatsomeof the layoutalgorithmsfor pla-nar graphsincludedin LEDA transformfirst the graphinto a planarmap,modifying againthe combinatorialembeddingof thegraph.Inparticular, applyingastraight-linelayoutor avisibility representationlayoutto anorderedtreetransformsit into adifferentorderedtree.

LEDA also provides efficient implementationsof algorithmsforplanargraphsandgraphdrawing algorithms.The readeris referredto [236, Chap.7–8] for details.

A.4 A SimpleRepresentationof Trees

The LEDA representationof graphsmay be usedfor representingtreesaswell, althoughLEDA graphsoffer many operationsthat donot make muchsensefor trees—forinstance,mostof thosedealingwith embeddedgraphs,becausea treehasonly oneface—andmorespace-efficient representationsfor treescouldbe adopted,asalready

Page 27: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.4 A SimpleRepresentationof Trees 427

discussedin Sect.1.4.Nevertheless,thechoicein this bookhasbeento defineasimpletreeclass,which inheritstherepresentationandop-erationsfrom thegraphclassandalsoprovidesadditionaloperationsfor trees.

Thetreeclassprovidesnonemptyrootedtrees.Thetree() construc-tor createsan empty tree,and the tree(G) constructorcreatesa treerepresentationof graphG, assumingG is thegraphrepresentationofa nonemptyrootedtree.All operationsprovided by the graph classcan be appliedto treesas well. Furtheroperationsprovided by thetreeclassareshown in Fig. A.30.

parent(v) returnstheparentof nodev, or nil if v is therootof thetreeis root(v) returnstrue if nodev is the root of the treeandfalseother-

wiseis leaf(v) returnstrueif nodev is a leafof thetreeandfalseotherwiseroot() returnstherootnodeof thetreefirst child(v) returnsthefirst child of nodev in thetree,or nil if v is a leaf

nodelast child(v) returnsthelastchild of nodev in thetree,or nil if v is a leaf

nodenext sibling(v) returnsthe next sibling of nodev in the tree,or nil if v is

eithertherootnodeor a lastchild of thetreeprevious sibling(v) returnstheprevioussiblingof nodev in thetree,or nil if v is

eithertherootnodeor a first child of thetreeis first child(v) returnstrue if nodev is a first child in the tree and false

otherwiseis last child(v) returnstrueif nodev is a lastchild in thetreeandfalseoth-

erwisenumberof children(v) returnsthenumberof childrenof nodev in thetree

Fig. A.30. Operationsprovidedby thetreeclass.

The treeclassincludesa default implementationderivedfrom theLEDA graphclass.Initializationfrom aLEDA graphtakesO

n time;

operationsparent, is root, is leaf, first child, last child, next sibling,previoussibling, is first child, is last child, numberof children takeO

1 time; root takes time linear in the depthof the tree;andclear

takesOn time, wheren is the sizeof the tree.The representation

usesOn space.

Recallfrom Sect.1.1thataconnectedundirectedgraphG V E

with n verticesandm edgesis anonemptyundirectedtreeif andonlyif n m 1. As a matterof fact, in an emptyundirectedtreebothn 0 andm 0.

Page 28: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

428 A. An Overview of LEDA

In thecaseof directed,rootedtrees,thepreviousconditionis stillnecessarybut no longersufficient for a graphto be a tree,becausea nodecouldhave morethanoneparent.Recallfrom Definition 1.36thataconnectedgraphT

V E is atreeif theunderlyingundirectedgraphhasnocyclesandfor all nodesv " V, thereis apathin thegraphfrom adistinguishednoderoot T to nodev.

Lemma A.1. A connectedgraph T V E with n verticesand m

arcsis a treeif andonly if n m 1 and indegv# 1 for all vertices

v " V.

Proof. Let T V E bea connectedgraphwith n verticesandm

n 1 arcssuchthat indegv$ 1 for all verticesv " V. Supposethat

indegv% 1 for all verticesv " V. Then,∑v & V indeg

v' ∑v & V 1 n.

But ∑v & V indegv( mby Theorem1.5,contradictingtheassumption

thatn m 1. Therefore,thereis avertex u " V with indegu) 0.

Now, sincethegraphis connectedthereis, for all verticesv " V, anundirectedpathfrom vertex u to vertex v. Supposethatthepathfromvertex u to somevertex v " V is not a directedpath.Then,theremustbesomevertex w " V alongthepathwith indeg

w* 2, contradicting

the assumptionthat indegv+ 1 for all verticesv " V. Therefore,

thereis adirectedpathfrom vertex u to vertex v, for all verticesv " V.Supposenow thatthereis acycle v1 ,, v2 - v1 in theunderly-

ing undirectedgraph.If thecycle is directed,vertex u cannotbelongto the cycle, becauseindeg

u. 0, and theremust be somevertex

w " V in thecyclesuchthatthedirectedpathfrom vertex u up to, butnot including,vertex w is disjoint from thecycle.Then,indeg

w/ 2,

contradictingtheassumptionthat indegv0 1 for all verticesv " V.

Otherwise,if the cycle is not directed,there must be somevertexw " V alongeither the undirectedpath v1 1 v2 or the undirectedpath v2 ,, v1 with indeg

w2 2, contradictingagainthe assump-

tion that indegv. 1 for all verticesv " V. Therefore,thereareno

cyclesin theunderlyingundirectedgraph,andT is indeeda tree.Conversely, let T

V E be a treewith n nodesandm arcs.ByTheorem1.43,n m 1.Supposenow thatthereis anodew " V withindeg

w2 1. Let v1 v2 " V be nodessuchthat

v1 w3

v2 w2" E,andlet v betheleastcommonancestorof nodesv1 andv2 in T. Then,the paths v1 v1 w and v1 v2 w togetherconstitutea cycle in

Page 29: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.4 A SimpleRepresentationof Trees 429

theunderlyingundirectedgraph,contradictingtheassumptionthatTis a tree.Therefore,indeg

v4 1 for all nodesv " V. 56

Thefollowing procedureis treereturnstrueif thegraphis therep-resentationof a rootedtreeandfalseotherwise.SincetheLEDA pro-cedureIs ConnectedtakesO

n time to determinewhetherthegraph

is connected,procedureis treealsotakesOn time.

429a 7 treegraphrepresentation429a89bool is tree(constgraph& G)nodev;forall nodes(v,G)if ( G.indeg(v) : 1 ) return false; // nonuniqueparent

return ( G.numberof nodes() ; G.numberof edges() + 1<Is Connected(G) );

The following treeclassis derived from the LEDA graph class.The destructor, copy constructor, and copy assignmentoperator, aswell as the operationson LEDA graphs,are all inherited from thegraphclass.

429b 7 treegraphrepresentation429a89=classtree: public graphpublic:tree() : graph()

tree( constgraph& G ) : graph( G )if ( > is tree(G) )error handler(1,"Graph is not a tree");

nodeparent( constnodev ) const;bool is root( constnodev ) const;bool is leaf( constnodev ) const;noderoot() const;nodefirst child( constnodev ) const;nodelast child( constnodev ) const;nodenext sibling( constnodev ) const;nodeprevious sibling( constnodev ) const;bool is first child( constnodev ) const;bool is last child( constnodev ) const;int numberof children( constnodev ) const;

;

Page 30: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

430 A. An Overview of LEDA

In the graphrepresentationof a tree T V E , the parentof a

nodev " V is theuniquenodeu " V suchthatu v#" E.

430a 7 treegraphrepresentation429a89=nodetree::parent( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;return ( ? this).source(( ? this).first in edge(v));

Theroot of a treeT V E is theonly nodev " V which is not

thetargetof any arcof theformu v*" E, thatis, theonly nodev " V

with indegv/ 0.

430b 7 treegraphrepresentation429a89=bool tree::is root( constnodev ) constreturn ( ? this).indeg(v) ; 0;

On the otherhand,a nodev " V is a leaf of a treeT V E if

thereis noarcof theformv w#" E, thatis, if outdeg

v* 0.

430c 7 treegraphrepresentation429a89=bool tree::is leaf( constnodev ) constreturn ( ? this).outdeg(v) ; 0;

The root of a treecanbe found in time linear in the depthof thetreeby startingoff with somenode—forinstance,a nodechosenatrandom—andthenfollowing thepathup to theroot of thetree.

Noticethatoperationrootcouldbeimplementedto takeO1 time

instead,by just extendingthe graphrepresentationof a treewith anexplicit pointerto therootnode.However, theroot of a treemuststillbe foundwhenreadingthe treefrom a LEDA graphwindow; for in-stance,in theinteractivedemonstrationof graphalgorithms.Besides,all algorithmson treesdiscussedin this booktake Ω

n timeanyway,

thetimeneededto eithergenerateor input thetree.430d 7 treegraphrepresentation429a89=

nodetree::root() constnodev = ( ? this).choosenode();while ( > is root(v) )v = parent(v);

Page 31: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.4 A SimpleRepresentationof Trees 431

return v;

Thefirst andthe lastchild of a nodein a treearethe targetof thefirst and the last arc going out of the node,respectively, accordingto the relative order of the children of the nodefixed by the graphrepresentationof thetree.

431a 7 treegraphrepresentation429a89=nodetree::first child( constnodev ) constif ( ( ? this).outdeg(v) ; 0 ) return nil;return ( ? this).target(( ? this).first adj edge(v));

431b 7 treegraphrepresentation429a89=nodetree::last child( constnodev ) constif ( ( ? this).outdeg(v) ; 0 ) return nil;return ( ? this).target(( ? this).last adj edge(v));

In the samesense,the next andthe previous sibling of a nodeina treearethe targetof thenext andthepreviousarcgoingout of theparentof thenode,respectively, accordingto therelative orderof thearcsgoingout of theparentnodefixedby thegraphrepresentationofthetree.

431c 7 treegraphrepresentation429a89=nodetree::next sibling( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;edge e = ( ? this).adj succ(( ? this).first in edge(v));if ( e ; nil ) return nil;return ( ? this).target(e);

431d 7 treegraphrepresentation429a89=nodetree::previous sibling( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;edge e = ( ? this).adj pred(( ? this).first in edge(v));if ( e ; nil ) return nil;return ( ? this).target(e);

Page 32: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

432 A. An Overview of LEDA

Now, thefirst child of theparentof anodeis saidto beafirstchildnode,andthelastchild of theparentof anodeis saidto bea lastchildnode.

432a 7 treegraphrepresentation429a89=bool tree::is first child( constnodev ) constif ( ( ? this).is root(v) ) return false;return ( ? this).first child(( ? this).parent(v)) ; v;

432b 7 treegraphrepresentation429a89=bool tree::is last child( constnodev ) constif ( ( ? this).is root(v) ) return true;return ( ? this).last child(( ? this).parent(v)) ; v;

Thenumberof childrenof a nodein a treeis just theoutdegreeofthecorrespondingvertex in thegraphrepresentationof thetree.

432c 7 treegraphrepresentation429a89=int tree::numberof children( constnodev ) constreturn ( ? this).outdeg(v);

Iterationoverall childrennodesw " V of nodev " V in a treeT V E is implementedby theLEDA macrofor iteratingoverthetarget

vertex w of all arcsof theformv w(" E in thegraphrepresentationof

thetree.In a macrocall of theform forall children(w,v), thechildrenof nodev aresuccessively assignedto nodew.

432d 7 treegraphrepresentation429a89=#define forall children(w,v) forall adj nodes(w,v)

A TREEclassis also defined,providing nonemptyrooted treesparametrizedby thetypeof theinformationassociatedwith thenodesandedgesof the tree.The TREEclassis derived from the GRAPHclasswhich is, in turn, derived from the graph class.The destruc-tor, copy constructor, and copy assignmentoperator, as well as theoperationson LEDA parametrizedgraphs,areall inheritedfrom theGRAPH class.Further operationsprovided by the TREE classareidenticalto theadditionaloperationsprovidedby the treeclass.

432e 7 treegraphrepresentation429a89=

Page 33: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.4 A SimpleRepresentationof Trees 433

template@ classV,classE :classTREE: public GRAPH@ V,E : public:TREE@ V,E : ()

TREE( constGRAPH@ V,E : & G ) : GRAPH@ V,E : ( G )if ( > is tree(G) ) error handler(1,"Graph is not a tree");

nodeparent( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;return ( ? this).source(( ? this).first in edge(v));

bool is root( constnodev ) constreturn ( ? this).indeg(v) ; 0;

bool is leaf( constnodev ) constreturn ( ? this).outdeg(v) ; 0;

noderoot() constnodev = ( ? this).choosenode();while ( > is root(v) )v = parent(v);

return v;

nodefirst child( constnodev ) constif ( ( ? this).outdeg(v) ; 0 ) return nil;return ( ? this).target(( ? this).first adj edge(v));

nodelast child( constnodev ) constif ( ( ? this).outdeg(v) ; 0 ) return nil;return ( ? this).target(( ? this).last adj edge(v));

nodenext sibling( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;edge e = ( ? this).adj succ(( ? this).first in edge(v));if ( e ; nil ) return nil;return ( ? this).target(e);

Page 34: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

434 A. An Overview of LEDA

nodeprevious sibling( constnodev ) constif ( ( ? this).indeg(v) ; 0 ) return nil;edge e = ( ? this).adj pred(( ? this).first in edge(v));if ( e ; nil ) return nil;return ( ? this).target(e);

bool is first child( constnodev ) constif ( ( ? this).is root(v) ) return false;return ( ? this).first child(( ? this).parent(v)) ; v;

bool is last child( constnodev ) constif ( ( ? this).is root(v) ) return true;return ( ? this).last child(( ? this).parent(v)) ; v;

int numberof children( constnodev ) constreturn ( ? this).outdeg(v);

;

A.5 A Simple Implementation of Radix Sort

Someof the algorithmsfor tree isomorphismand relatedproblemsdiscussedin Chap.4, requiredradixsortingalist of arraysof integers.Radix sort is basedon bucket sort,andconsistsof sortingthe list ofarraysof integersin severalstages,usingbucketsortat eachstage.

Bucket Sort

LEDA doesnot provide an implementationof radix sort,althoughitincludesanefficient implementationof bucketsortwhich is, however,of a ratherlow level. The following, straightforward implementationof bucket sort is a moreconvenientstartingpoint for a simpleLEDAimplementationof radixsort.

Let ord: E A int bea functionwith ordx#"B i j for all elements

x of list L. Bucket sortingL consistsof maintainingan arraybucket

Page 35: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.5 A SimpleImplementationof RadixSort 435

of j i 1 lists of elements,initially empty;appendingeachelementx of L to bucket numberk ord

x( i 1; andthencollecting the

elementsin sortedorderby concatenatingall thebucketsbackinto asinglelist.

The following algorithmsortsthe elementsof list L usingbucketsort,implementingthepreviousprocedure.Theelementsof L aredis-tributedinto buckets,andthebucketsareconcatenatedbackinto thesortedlist L. Theidentity functionis providedasdefault valuefor theord parameter. Spaceefficiency of the implementationfollows frombothpopandconcoperationsbeingdestructive.

435 7 subroutines408CDtemplate@ classE :void straight bucket sort(list @ E : & L,int i,int j,int ( ? ord)(constE&) = id)int n = j i + 1; // numberof bucketsneededarray@ list @ E :=: bucket(1,n);while ( > L.empty() ) E x = L.pop();int k = ord(x) i + 1; // elementx belongsin bucket kif ( k E 1

<k n )

bucket[k].append(x); elseerror handler(1,"bucket sort: value out of range");

for ( i = 1; i n; i FGF )L.conc(bucket[i]); // destructive7 double-checkbucket sort436b8

RemarkA.2. Notice that bucket sort is a stablesortingmethod,thatis, if ord

xH ord

y andx precedesy in L, thenx alsoprecedesy in

thebucket sortedlist L, for all elementsx andy of L. As a matteroffact, in the previous bucket sortingalgorithm,the elementsof L areappendedto appropriatebucketsin order, andthis orderis preservedwhenconcatenatingthebuckets.

Bucket sort is oftencalledjust on a list of elements.A procedurecall of the form straight bucket sort(L,ord) is thesameastheproce-durecall straight bucket sort(L,i,j,ord), wherei and j arerespectively

Page 36: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

436 A. An Overview of LEDA

theminimumandmaximumvaluesof ordx asx rangesover theel-

ementsof list L. Again, the identity function is provided asdefaultvaluefor theord parameter.

436a 7 subroutines408CDtemplate@ classE :void straight bucket sort(list @ E : & L,int ( ? ord)(constE&) = id)if ( L.empty() ) return;int i = ord(L.head());int j = i;E x;forall(x,L) int k = ord(x);if ( k @ i ) i = k;if ( k : j ) j = k;straight bucket sort(L,i,j,ord);

Thefollowing double-checkof bucket sort,althoughbeingredun-dant,givessomereassuranceof thecorrectnessof theimplementation.It verifiesthatL is sorted,thatis, thatord

x/ ord

succ

x for all but

thelastelementx of list L.436b 7 double-checkbucket sort436b89

list itemit;forall items(it,L) if ( it I L.last()

<ord(L[it]) : ord(L[L.succ(it)]) )

error handler(1,"Wrong implementation of bucket sort");

Lemma A.3. Thealgorithm for bucket sorting runs in On j i

time usingOj i additional space, where n is the lengthof list L

and i j are respectivelytheminimumandmaximumvaluesof ordx

asx rangesover theelementsof L.

Proof. The first loop rangesover the elementsof L, and thus takesO

n time, andthe secondloop rangesover the buckets,thustaking

Oj i time.Therefore,thealgorithmrunsin O

n j i time.Fur-

ther, thealgorithmusesOj i additionalspace,becauseanarrayof

j i 1 bucketsis first allocated,theelementsof L arepoppedfrom L

Page 37: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.5 A SimpleImplementationof RadixSort 437

andappendedto their respectivebucket,andthebucketsareconcate-natedbackinto L, wherebothpopandconcoperationsaredestructive.

Thedouble-checkof bucket sortingrunsin On time usingO

1

additionalspace. 56It follows that j i n is a sufficient conditionfor bucket sort to

run in On time.

Corollary A.4. Thealgorithm for bucket sorting runs in On time

upona list L of n elementsif j i n, where ordx2"J i j for all

elementsx of L.

Radix Sort

Radixsort is a stablesortingmethodconsistingof k passesof bucketsort,on thelastelement,theprevious-to-lastelement,andsoon,untilbucket sortingon the first elementof eachlist, wherek is the maxi-mumamongthelengthsof thelistsof integersto besorted.Sincesucha procedurerequiresdirectaccessto individual elementsin eachlist,though,thelist of lists of integersto besortedis representedby a listof arraysof integersinstead.

ExampleA.5. Radixsortingthelist of arraysof integers 83 79 82 84K 73 78 71L 73 78KM 76 73 78L 69 65 82LN 84 73 77 69 ,whicharethe ASCII codesof the charactersin the list of characterstrings[SORT,ING, IN, LIN, EAR, TIME], proceedsasfollows.

SORTINGINLINEARTIME

'A

INGINLINEARTIMESORT

'A

ININGTIMELINEARSORT

'A

EARTIMELINININGSORT

'A

EARININGLINSORTTIME

Theleftmostcolumnshowsthelist of characterstringscorrespondingto thelist of arraysof integersto besorted,andtheremainingcolumnsshow theresultof bucketsortingon increasinglysignificantcharacterpositions.Thecharacterpositionbucketsortedonto produceeachlistof characterstringsfrom thepreviousoneis highlighted.

Page 38: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

438 A. An Overview of LEDA

RemarkA.6. Thepreviousalgorithmis known asLSD (leastsignifi-cantdigit) radixsort,becausetheleastsignificantelementin thearraysof integersis bucket sortedfirst. MSD (mostsignificantdigit) radixsort,on thecontrary, consistsof bucketsortingonthemostsignificantelementfirst, andthenradixsortingeachgroupof arraysuffixesshar-ing acommonfirst element.While with LSD radixsortall elementsofthearraysareinspected,only thedistinguishingprefixesof thearraysareinspectedwith MSD radixsort,althoughat theexpenseof decom-posingthesortingprobleminto a largenumberof subproblems.WithLSD radixsort,bucketsortingis appliedseveraltimesto thesamelistof arraysof integersinstead.

Now, given a list L of n arraysof at mostk integerseach,whereord

xH"O i j for all integersx in eacharrayin list L and j i n, the

previous radix sortingalgorithmstill makesk passesof bucket sort,eachtaking O

n time, andthereforerunsin O

kn time. This is ef-

ficient whenall arrayshave approximatelythe samelength,becausethe total lengthof the arraysof integersto be sortedis ∑n

i 1Ok 0

O∑n

i 1k ( Okn . However, radixsortinga list L of n arraysof inte-

gers,oneof themof lengthn andtheotheronesof only afew integers,would takeO

n2 time,althoughthetotal lengthof thearraysof inte-

gersto besortedis, in this case,OnP ∑n

i 2O1* O

n .

The reasonfor the lack of efficiency is that in the previous radixsortingalgorithm,alargenumberof emptybucketsmightbeinspectedat eachpassof bucket sort.Nevertheless,thepreviousalgorithmcanbeextendedto asimpleradixsortingalgorithmrunningin time linearin thetotal lengthof thearraysof integersto besorted,asfollows.

Let maxlenbe the maximumlengthamongall arraysof integersto besorted.Inspectingemptybucketscanbeavoidedby building foreachposition i in the arrays,with 1 i maxlen,a list LEN[i] ofthe arraysof length i andalso a sortedlist FULL[i] of the integersappearingat the ith positionin thearrays.

Then,bucket sortingthelist L of arrayson the ith componentpro-ceedsby concatenatingat the front of L the list LEN[i] of arraysoflengthi, distributing theresultinglist L into bucketsaccordingto theith componentand,finally, concatenatingback into L all nonemptybuckets,thatis, thosebucketscorrespondingto FULL[i].

Page 39: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.5 A SimpleImplementationof RadixSort 439

ExampleA.7. Moreefficient radix sortingof thelist of arraysof inte-gersof ExampleA.5, which aretheASCII codesof thecharactersinthelist of characterstrings[SORT, ING, IN, LIN, EAR, TIME].

SORTINGINLINEARTIME

a'A TIMESORT

b'A

INGTIMELINEARSORT

c'A

EARTIMELINININGSORT

d 'A

EARININGLINSORTTIME

a List LEN 4 ;L Q SORT TIME ; R is distributedinto bucketsaccord-

ing to thefourth component,but only thosebucketscorrespondingtoFULL 4(S E T are concatenatedback into L.

b List LEN 3 ;L

ING LIN EAR ; TIME SORT is distributedinto bucketsaccordingtothethird component,but only thebucketscorrespondingto FULL 3M G M N R areconcatenatedbackintoL.

c List LEN 2 ;L T IN ; ING

TIME LIN EAR SORT is distributedinto bucketsaccordingto thesec-ond component,but only thosebucketscorrespondingto FULL 2U A I N O areconcatenatedbackinto L.

d List LEN 1 ;L VR ; EAR

TIME LIN IN ING SORT is distributedinto bucketsaccordingto thefirst component,but only thosebucketscorrespondingto FULL 1U E I L S T areconcatenatedbackinto L.

Nonemptybuckets can be found, as a matterof fact, by bucketsorting.Let P bea list of pairs W i A i CX for all arraysA in list L, with1 i maxlen. After bucketsortingPonthesecondpositionandthenon thefirst position,a sortedlist (without duplicates)FULL[i] of theintegersin the ith positionof the arrayscanbe obtained,indicatingwhich bucketswill be nonemptyduring the radix sort, whenbucketsortingon the ith positionof thearrays.

ExampleA.8. Finding nonemptybuckets for a more efficient radixsortingof thelist of arraysof integersof ExampleA.7, which aretheASCII codesof the charactersin the list of characterstrings[SORT,ING, IN, LIN, EAR, TIME].

Page 40: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

440 A. An Overview of LEDA

SORTINGINLINEARTIME

a%A

W 1 S XW 2 O XW 3 R XW 4 T XW 1 I XW 2 N XW 3 G XW 1 I XW 2 N XW 1 L XW 2 I XW 3 N XW 1 E XW 2 A XW 3 R XW 1 T XW 2 I XW 3 M XW 4 E X

b'A

W 2 A XW 1 E XW 4 E XW 3 G XW 1 I XW 1 I XW 2 I XW 2 I XW 1 L XW 3 M XW 2 N XW 2 N XW 3 N XW 2 O XW 3 R XW 3 R XW 1 S XW 4 T XW 1 T X

cYA

W 1 E XW 1 I XW 1 I XW 1 L XW 1 S XW 1 T XW 2 A XW 2 I XW 2 I XW 2 N XW 2 N XW 2 O XW 3 G XW 3 M XW 3 N XW 3 R XW 3 R XW 4 E XW 4 T X

d 'A

EIILST

AIINNO

GMNRR

ET

e'A E I L S T A I N O G M N R E T

a Extractinga list P of pairs W i A i 9X for all arraysA in list L, with

1 i 4.b Bucketsortinglist P by thesecondposition.

c Bucket

sortingtheresultinglist P by thefirst position.d Extractingasorted

list FULL[i] of the integersin the ith positionof the arrays.e Re-

moving duplicatesfrom eachsortedlist FULL[i].

The following algorithmsortsthe arraysof integersof list L us-ing radixsort,implementingthepreviousprocedure.In orderto avoidusinga new bucket arrayfor eachpassof bucket sort,a singlearraybucket of lists of arraysof integersis usedthroughoutthewholepro-cedure,andthe list P of pairs W i A i 9X is alsorepresentedby a list ofarraysof integers.

440 7 subroutines408CDvoid radix sort(list @ array@ int :Z: & L,int min,int max)if ( L.empty() ) return;7 computenumbern of bucketsneeded441a8

Page 41: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.5 A SimpleImplementationof RadixSort 441

array@ list @ array@ int :=:=: bucket(1,n);7 find nonemptybuckets441b87 distributearraysby length442c8for ( int i = maxlen; i E 1; i [G[ ) 7 bucket sortlist L of arrayson ith component443a87 double-checkradixsort443c8

Thenumberof bucketsneededis thelargestof max min 1 andmaxlen, themaximumlengthamongall arraysA in list L.

441a 7 computenumbern of bucketsneeded441a89int maxlen= 0;array@ int : A,T;forall(A,L)maxlen= leda max(maxlen,A.size());

int n = leda max(max min + 1,maxlen);

Nonemptybucketsarefoundby (a)building alist Pof pairs W i A i 9Xfor all arraysA in list L, with 1 i maxlen; (b) bucketsortinglist Ponthesecondcomponentandthenonthefirst component;(c) collect-ing thesecondcomponentof eachpair of thesortedlist P in a sortedlist FULL[i] of integers;and(d) makingeachlistsFULL[i] uniquebyremoving duplicates.

Notice thatduplicatescanberemovedin time linear in the lengthof the list usingthe LEDA procedureunique, becauselists FULL[i]aresorted.

441b 7 find nonemptybuckets441b897 make list P of pairs(i,A[i]) 441c87 bucket sort list P of pairsby A[i] 442a87 bucket sort list P of pairsby i 442b8array@ list @ int :=: FULL(1,maxlen);forall(A,P)FULL[A[1]].append(A[2]);

for ( int i = 1; i maxlen; i F\F )FULL[i].unique();

Recall that the list of pairs W i A i CX is representedby a list P ofarraysT ] i A i of integers,in orderto usethe samearraybucketof lists of arraysof integersfor bucket sorting throughoutthe radixsortingalgorithm.

441c 7 make list P of pairs(i,A[i]) 441c8Rlist @ array@ int :=: P;

Page 42: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

442 A. An Overview of LEDA

forall(A,L) for ( int i = 1; i A.size(); i FGF ) array@ int : T(1,i,A[i]);P.append(T);

Whenbucketsortingthelist P of arraysT of integersby thesecondcomponent,arrayT ^ i A i belongsin bucketA i _ min 1.

442a 7 bucket sort list P of pairsby A[i] 442a8`while ( > P.empty() ) T = P.pop();int k = T[2] min + 1; // T belongsin bucket kif ( k E 1

<k n )

bucket[k].append(T); elseerror handler(1,"radix sort: value out of range");

for ( int i = 1; i n; i F\F )P.conc(bucket[i]); // destructive

Whenbucket sortingthe list P of arraysT of integersby thefirstcomponent,on theotherhand,arrayT a i A i belongsin bucket i.

442b 7 bucket sort list P of pairsby i 442b89while ( > P.empty() ) T = P.pop();int k = T[1]; // T belongsin bucket kif ( k E 1

<k n )

bucket[k].append(T); elseerror handler(1,"radix sort: value out of range");

for ( int i = 1; i n; i F\F )P.conc(bucket[i]); // destructive

Distributing the list L of arraysA of integersinto lists LEN[i] ofarraysof lengthi is straightforward.An arrayA of lengthi belongsinLEN i .

442c 7 distributearraysby length442c89array@ list @ array@ int :D:Z: LEN(1,maxlen);while ( > L.empty() ) A = L.pop();LEN[A.size()].append(A);

Page 43: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

A.5 A SimpleImplementationof RadixSort 443

Now, bucketsortingthelist L of arraysatcomponenti canbedoneby first concatenatingall arraysof lengthi at thefront of L, thendis-tributingL into bucketsaccordingto theintegersat theith componentand,finally, concatenatingall nonemptybucketsbackinto L.

443a 7 bucket sort list L of arrayson ith component443a89L.conc(LEN[i],LEDA::before); // destructivewhile ( > L.empty() ) A = L.pop();int k = A[i] min + 1; // arrayA belongsin bucket kif ( k E 1

<k n )

bucket[k].append(A); elseerror handler(1,"radix sort: value out of range");

int x;forall(x,FULL[i])L.conc(bucket[x min+ 1]); // destructive

Radix sort is often called just on a list of arraysof elements.Aprocedurecall of theform radix sort(L) is thesameastheprocedurecall radix sort(L,i,j), wherei and j arerespectively theminimumandmaximumelementsamongall arraysin list L.

443b 7 subroutines408CDvoid radix sort(list @ array@ int :Z: & L)if ( L.length() 1 ) return;if ( L.head().size() ; 0 ) return;int i = L.head()[1];int j = i;array@ int : A;int x;forall(A,L) forall(x,A) i = leda min(i,x);j = leda max(j,x);

radix sort(L,i,j);

The following double-checkof radix sort, althoughbeingredun-dant,givessomereassuranceof the correctnessof the implementa-tion. It verifies that L is sortedin lexicographicorder, that is, thatA succ

A for all but thelastarrayof integersA of thelist of arrays

of integersL.

Page 44: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

444 A. An Overview of LEDA

443c 7 double-checkradixsort443c89 list itemit;forall items(it,L) if ( it I L.last()

<L[it] : L[L.succ(it)] )

error handler(1,"Wrong implementation of radix sort");

RemarkA.9. Correctnessof radixsortingfollowsfrom bucketsortbe-ing astablesortingmethod.

Lemma A.10. Thealgorithm for radix sorting runs in On j i

time using Omax

n j i additional space, where n is the total

lengthof the arrays in list L and i and j are respectivelythe mini-mumandmaximumelementsamongall arraysin list L.

Proof. Let L be the list of m arraysof integersto be sorted,let n bethe total lengthof thearraysin list L, andlet i and j be respectivelytheminimumandmaximumelementsamongall arraysin list L. LetalsoP bea list of pairs W k A k9X for all arraysA in list L.

List P is built in On time, andnonemptybucketsare found in

On j i time by two passesof bucket sortuponlist P. Then,for

eachcomponentk in thearrays,bucket sortinglist L on thekth com-ponenttakestime linearin thenumberof arraysA with length AU kand therefore,bucket sorting list L on all arraycomponentstakesatotal of O

n j i time. Further, O

max

n j i additionalspace

is usedfor storingthearrayof buckets,which is sharedby all passesof bucket sort.

The double-checkof radix sorting makes m array comparisons,whereeachcomparisontakestime linear in the lengthof the arrays,andthereforerunsin O

n time,usingO

1 additionalspace. 56

A few implementationdetailsstill needto befilled in, though.Thedouble-checkof radix sort requiresthe lexicographiccomparisonofarraysof integers,andthefollowing proceduredefines,then,adefaultlinearorderfor LEDA arraysof integers.Giventwo arraysof integersA1 andA2, it returns 1 if A1 is smallerin lexicographicorderthanA2, 0 if the arraysA1 and A2 are identical,and 1 if A1 is larger inlexicographicorderthanA2.

Page 45: A. An Overview of LEDA - Computer Science …valiente/algorithm/leda.pdf · A. An Overview of LEDA Libraries are great; ... the Boost Graph Library [209, 302] that is be- ... with

Reprinted from "Algorithms onTrees and Graphs" by Gabriel Valiente. (c) 2002 Springer-Verlag.

BibliographicNotes 445

444 7 default procedures44489int compare(constarray@ int : & A1,constarray@ int : & A2)int n = leda min(A1.size(),A2.size());for ( int i = 1; i n; i F\F ) if ( A1[i] @ A2[i] ) return 1;if ( A1[i] : A2[i] ) return 1;if ( A1.size() @ A2.size() ) return 1;if ( A1.size() : A2.size() ) return 1;return 0;

Now, thefollowing Booleancomparisonoperatorfor arraysof in-tegersmakesit possibleto testanarrayfor beinglarger thananotherone.

445 7 default procedures44489Dbool operator : (constarray@ int : & A1,constarray@ int : & A2)return compare(A1,A2) ; 1;

Bibliographic Notes

See[234,236] for acomprehensivedescriptionof LEDA. Thesimpleimplementationof radix sort is basedon [233,Sect.2.2]. Seealso[8,9, 36,87,195, 230,373,374].