id
int64
0
25.6k
text
stringlengths
0
4.59k
23,200
weighted graphs the third agentin danza at this pointthe cheapest route you know that goes from ajo to any town without an agent is $ the direct route from ajo to danza both the ajo-bordo-colina route at $ and the ajo-bordo-danza route at $ are more expensive you hire another passerby and send her to danzawith an $ tic...
23,201
ajo-danza-colina-erizo routeyou update your notebook accordinglyas shown in table and figure $ $ $ $ $ $ $ $ $ figure following step in the shortest-path algorithm table step agents in ajobordodanzaand colina from ajo tobordo colina danza erizo step step step step (via ajo (via ajo) (via ajo) (via ajo)inf (via bordo (v...
23,202
weighted graphs when there' an agent in every townyou know the fares from ajo to every other town so you're done with no further calculationsthe last line in your notebook shows the cheapest routes from ajo to all other towns this narrative has demonstrated the essentials of dijkstra' algorithm the key points are each ...
23,203
the shortest-path array an additional click of the path button will install table under the graphas you can see in figure the corresponding message is copied row from adjacency matrix to shortest-path array dijkstra' algorithm starts by copying the appropriate row of the adjacency matrix (that isthe row for the startin...
23,204
weighted graphs column by column in the shortest-path array now the algorithm knows not only all the edges from abut the edges from as well so it goes through the shortest-path arraycolumn by columnchecking whether shorter path than that shown can be calculated using this new information vertices that are already in th...
23,205
new minimum distance now that the shortest-path array has been updatedthe algorithm finds the shortest distance in the arrayas you will see with another path keypress the message is minimum distance from is to vertex accordinglythe message added vertex to tree appears and the new vertex and edge ac are added to the tre...
23,206
weighted graphs java code the code for the shortest-path algorithm is among the most complex in this bookbut even so it' not beyond mere mortals we'll look first at helper class and then at the chief method that executes the algorithmpath()and finally at two methods called by path(to carry out specialized tasks the spa...
23,207
public void path(/find all shortest paths int starttree /start at vertex vertexlist[starttreeisintree truentree /put it in tree /transfer row of distances from adjmat to spath for(int = <nvertsj++int tempdist adjmat[starttree][ ]spath[jnew distpar(starttreetempdist)/until all vertices are in the tree while(ntree nverts...
23,208
weighted graphs the starting vertex is always at index of the vertexlist[array the first task in path(is to put this vertex into the tree as the algorithm proceedswe'll be moving other vertices into the tree as well the vertex class contains flag that indicates whether vertex object is in the tree putting vertex in the...
23,209
mindist spath[jdistanceindexmin /update minimum /end for return indexmin/return index of minimum /end getmin(we could have used priority queue as the basis for the shortest-path algorithmas we did in the previous section to find the minimum spanning tree if we hadthe getmin(method would not have been necessarythe minim...
23,210
weighted graphs /calculate distance for one spath entry /get edge from currentvert to column int currenttofringe adjmat[currentvert][column]/add distance from start int starttofringe starttocurrent currenttofringe/get distance of current spath entry int spathdist spath[columndistance/compare distance from start with sp...
23,211
the output of this program is =inf(ab= (ac= (dd= (ae= (cthe path java program listing shows the complete code for the path java program its various components were all discussed earlier listing the path java program /path java /demonstrates shortest path with weighteddirected graphs /to run this programc>java pathapp /...
23,212
weighted graphs listing continued private final int infinity private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private int ntree/number of verts in tree private distpar spath[]/array for shortest-path data private int currentvert/current v...
23,213
listing continued int tempdist adjmat[starttree][ ]spath[jnew distpar(starttreetempdist)/until all vertices are in the tree while(ntree nvertsint indexmin getmin()/get minimum from spath int mindist spath[indexmindistanceif(mindist =infinity/if all infinite /or in treesystem out println("there are unreachable vertices"...
23,214
weighted graphs listing continued if!vertexlist[jisintree &/smaller than old one spath[jdistance mindist mindist spath[jdistanceindexmin /update minimum /end for return indexmin/return index of minimum /end getmin(/public void adjust_spath(/adjust values in shortest-path array spath int column /skip starting vertex whi...
23,215
listing continued for(int = <nvertsj++/display contents of spath[system out print(vertexlist[jlabel "=")/bif(spath[jdistance =infinitysystem out print("inf")/inf else system out print(spath[jdistance)/ char parent vertexlistspath[jparentvert labelsystem out print("(parent "")/(asystem out println("")//end class graph /...
23,216
weighted graphs the all-pairs shortest-path problem in discussing connectivity in we wanted to know whether it was possible to fly from athens to murmansk if we didn' care how many stops we made with weighted graphs we can answer the second question that might occur to you as you wait at the hubris airlines ticket coun...
23,217
from figure that we can go from to at cost of ( from to plus from to cas in warshall' algorithm we systematically modify the adjacency matrix we examine every cell in every row if there' non-zero weight (say at row column )we then look in column (because is the row where the isif we find an entry in column (say at row ...
23,218
weighted graphs efficiency so far we haven' discussed the efficiency of the various graph algorithms the issue is complicated by the two ways of representing graphsthe adjacency matrix and adjacency lists if an adjacency matrix is usedthe algorithms we've discussed mostly require ( timewhere is the number of vertices w...
23,219
howeversome algorithms have big values that are so large that they can be used only for relatively small values of many real-world problems that require such algorithms simply cannot be solved in reasonable length of time such problems are said to be intractable (another term used for such problems is np completewhere ...
23,220
weighted graphs figure cities and distances to find the shortest routeyou list all the possible permutations of cities (bostonseattle-miamiboston-miami-seattlemiami-boston-seattleand so onand calculate the total distance for each permutation the route abceda has total length of the route abcdea is impossible because th...
23,221
summary in weighted graphedges have an associated number called the weightwhich might represent distancescoststimesor other quantities the minimum spanning tree in weighted graph minimizes the weights of the edges necessary to connect all the vertices an algorithm using priority queue can be used to find the minimum sp...
23,222
weighted graphs true or falsethe weight of the mst depends on the starting vertex in the mst algorithmwhat is removed from the priority queue in the cable tv exampleeach edge added to the mst connects the starting vertex to an adjacent vertex an already-connected city to an unconnected city the current vertex to an adj...
23,223
floyd' algorithm is to weighted graphs what is to unweighted graphs floyd' algorithm uses the representation of graph what is an approximate big time for an attempt to solve the knight' tour in figure is the route abceda the minimum solution for the traveling salesman problemexperiments carrying out these experiments w...
23,224
weighted graphs table of the graph to prove that the graph is constructed properly you'll need to store the weight of each edge somewhere one approach is to use an edge classwhich stores its weight and the vertex on which it ends each vertex then keeps list of edge objects--that isedges that start on that vertex implem...
23,225
when to use what in this general-purpose data structures special-purpose data in this we briefly summarize what we've learned so farwith an eye toward deciding what data structure or algorithm to use in particular situation this comes with the usual caveats of necessityit' very general every real-world situation is uni...
23,226
when to use what structures because they are used to store and retrieve data using key values this works for general-purpose database programs (as opposed to specialized structures such as stackswhich allow access to only certain data itemswhich of these general-purpose data structures is appropriate for given problemf...
23,227
processor speeda moving target the fast structures come with penaltiesand another development makes the slow structures more attractive every year there' an increase in the cpu and memoryaccess speed of the latest computers moore' law (postulated by gordon moore in specifies that cpu performance will double every month...
23,228
when to use what using commercial library may eliminate or at least reduce the programming necessary to create the data structures described in this book when that' the caseusing complex structure such as balanced treeor delicate algorithm such as quicksortbecomes more attractive possibility howeveryou must ensure that...
23,229
( )which is the maximum for any data structure (by definitionyou must visit every itemyou can also find the minimum and maximum quickly and traverse range of items an unbalanced binary tree is much easier to program than balanced treebut unfortunately ordered data can reduce its performance to (ntimeno better than link...
23,230
when to use what comparing the general-purpose storage structures table summarizes the speeds of the various general-purpose data storage structures using big notation table general-purpose data storage structures data structure search insertion deletion traversal array ordered array linked list ordered linked list bin...
23,231
these adts can be seen as conceptual aids their functionality could be obtained using the underlying structure (such as an arraydirectlybut the reduced interface they offer simplifies many problems these adts can' be conveniently searched for an item by key value or traversed stack stack is used when you want access on...
23,232
when to use what use an array or double-ended linked list if insertion speed is not problem the array works when the amount of data to be stored can be predicted in advancethe linked list when the amount of data is unknown if speed is importanta heap is better choice comparison of special-purpose structures table shows...
23,233
dataheapsort is better quicksort is also prone to subtle errors if it is not implemented correctly small mistakes in coding can make it work poorly for certain arrangements of dataa situation that may be hard to diagnose table summarizes the running time for various sorting algorithms the column labeled comparison atte...
23,234
when to use what storagewhich generally means disk files we discussed external storage in the second parts of trees and external storage,and "hash tables we assumed that data is stored in disk file in fixed-size units called blockseach of which holds number of records ( record in disk file holds the same sort of data a...
23,235
deletion of records in (logntime this is quite fast and works even for very large files howeverthe programming is not trivial hashing if it' acceptable to use about twice as much external storage as file would normally takethen external hashing might be good choice it has the same access time as indexed fileso( )but ca...
23,236
when to use what you can apply internal algorithms to the entire file just as if it was all in memory at the same timeand let the operating system worry about reading the appropriate part of the file if it isn' in memory already of courseoperation will be much slower than when the entire file is in memorybut this would...
23,237
running the workshop applets and example programs in this appendix the workshop applets the example programs the sun microsystem' software development kit multiple class files other development systems in this appendix we discuss the details of running the workshop applets and the example programs the workshop applets ...
23,238
appendix running the workshop applets and example programs in this bookthe workshop applets provide dynamicinteractive graphics-based demonstrations of the concepts discussed in the text for example"binary trees,includes workshop applet that shows tree in the applet window clicking the applet' buttons will show the ste...
23,239
command-line programs the sdk operates in text modeusing the command line to launch its various programs in windowsyou'll need to open an ms-dos box to obtain this command line click the start buttonand find the program called ms-dos prompt it may be in the accessories folderand it may be called something elselike comm...
23,240
appendix running the workshop applets and example programs as we notedyou can also use most web browsers to execute the applets operating the workshop applets each gives instructions for operating specific workshop applets in generalremember that in most cases you'll need to repeatedly click single button to carry out ...
23,241
don' type file extension after the filename the insertsort program should runand you'll see text display of unsorted and sorted data in some example programs you'll see prompt inviting you to enter inputwhich you type at the keyboard compiling the example programs you can experiment with the example programs by modifyi...
23,242
appendix running the workshop applets and example programs invoking the wrong file should not normally be problem because all the files for given program are placed in the same subdirectory howeverif you move files by handbe careful not to inadvertently copy file to the wrong directory doing this may cause problems tha...
23,243
further reading in this appendix data structures and algorithms object-oriented in this appendix we'll mention some books on various aspects of software developmentincluding data structures and algorithms this is subjective listthere are many other excellent titles on all the topics mentioned data structures and algori...
23,244
appendix further reading projects the java version is data abstraction and problem solving with javawalls and mirrors by frank carrano and janet prichard practical algorithms in +by bryan flamig (john wiley and sons covers many of the usual topics in addition to some not frequently covered by other bookssuch as algorit...
23,245
classic in the field of ood is object-oriented analysis and design with applications by grady booch (addison wesley the author is one of the pioneers in this field and the creator of the booch notation for depicting class relationships this book isn' easy for beginnersbut is essential for more advanced readers an early...
23,246
answers to questions in this appendix overview arrays simple sorting stacks and queues overview answers to questions linked lists recursion insertsearch fordelete advanced sorting sorting binary trees red-black trees search key trees and external storage hash tables heaps method graphs dot weighted graphs data types ar...
23,247
appendix answers to questions interface raising to power false constant objects simple sorting answers to questions comparing and swapping (or copying false false false three items with indices less than or equal to outer are sorted copies items with indices less than outer are partially sorted
23,248
stacks and queues answers to questions last-in-first-outand first-in-first-out false it' the other way around it doesn' move at all false they take ( time ( true yesyou would need method to find the minimum value linked lists answers to questions first current next=null java' garbage collection process destroys it
23,249
appendix answers to questions empty linked list onceif the links include previous reference double-ended list usuallythe list they both do push(and pop(in ( timebut the list uses memory more efficiently recursion answers to questions false "ed divide-and-conquer the range of cells to search the number of disks to trans...
23,250
advanced sorting answers to questions false ( *logn) ( pivot true partitioning the resulting subarrays pivot log true binary trees answers to questions (logn true nodetree
23,251
appendix answers to questions finding aa' left-child descendents * + false compress red-black trees answers to questions in order (or inverse order false rotationschanging the colors of nodes red left childright child nodeits two children true true
23,252
trees and external storage answers to questions balanced false the root is split color flip (logn many true hash tables answers to questions ( hash function linear probing linked list
23,253
appendix answers to questions true the array size false false the same block heaps answers to questions both the right and left children have keys less than (or equal tothe parent root array (or linked list up one graphs answers to questions edgenodes (or vertices count the number of and divide by (assuming the identit...
23,254
node :bb: --> -->dc:bd: tree no true directed acyclic graph noby definition some vertices remainbut none have no successors weighted graphs answers to questions edges false the lowest-weight (cheapestedge is already the destination of an edge with lower weight false true warshall' algorithm
23,255
appendix answers to questions adjacency matrix nwhere is the number of squares on the board minus no
23,256
symbols (dot operator) (assignment operator) =(equality operator) (modulo operator)hashing - trees implementation - node splits - trees - balance efficiency speed storage requirements experiments insertion java code dataitem class node class tree class tree app class node splits - nodes per organization red-black trees...
23,257
trees tree workshop applet fill button find button partition - efficiency - stopping/swapping - ins button quicksort - zoom button - recursion tree java recursive (towers of hanoi) stable all-pairs shortest-path problemweighted graphs - anagram java abstract data type abstraction adts class interfaces access modifiers ...
23,258
insert start button remove text messages insertsort workshop selectsort workshop bars shellsort - bars stack workshop linklist workshop new deleting peek find pop inserting push sorted lists size mergesort - towers ordered workshop tree workshop - binary search tree workshop linear search fill button partition workshop...
23,259
arrays creating example (array java) - deletion -trees (external storage) displaying choosing insertion efficiency - program organization insertion - searching one block per node hashing dictionary example searching balanced trees heap java avl holes choosing initializing bank java code listing - internalexternal stora...
23,260
binary trees tree java analogy workshop applet - as arrays - binary treesnodes choosing binarysearch java duplicate keys black height efficiency heaps color flips blocks - huffman code - full java code hashing and external storage - node class insertion tree class sorting external files treeapp class booksresource - ma...
23,261
child (binary treeschild (binary trees) children tree inserting trees searching red-black treesnull children splitting unbalanced trees chng key circular queues classes tree app treeapp vertex clustering bankaccount open addressing bankapp quadratic probes data types dataitem distpar dividing programs into - collisions...
23,262
links delete(method data records data storage data structures find(method nodes red-black trees characteristics with no children general purpose with one child - arrays with two children - balanced trees priorityq workshop applet big notation separate chaining binary search trees hash tables vertices delimiter matching...
23,263
display(method display(methodhigharray class displayforward(methoddoubly linked list displaylist(methoditerators edges displaynode(method adding displayperson(method minimum spanning trees displaystack(method minimum spanning trees for weighted graphs displayword(method distpar class divide-and-conquer approach doanagr...
23,264
hashing finding full blocks linklist workshop applet non-full blocks links table of file pointers delete(method indexing find(method file in memory nodes multiple efficiency searching java code - too large workshop applet - search criteria firstlastlist java sequential ordering - flip buttonrbtree workshop sorting exte...
23,265
getmin(method getmin(method traces getsuccessor(method trees graph class - vertices graphdw workshop applet - adding shortest-path array deleting graphn workshop applet weighted dfs minimum spanning trees graphs - see also weighted graphs graphw workshop applet - guess- -number game adjacency choosing connected critica...
23,266
separate chaining insert employee numbers (keys) external remove heapsort external storage - efficiency open addressing recursion double hashing - heapsort java linear probing - - higharray class quadratic probing higharray java separate chaining hoarec hashchain applet - holes java code horner' method heap java huffma...
23,267
infix notation java code - nodes operatorssaving on stack heaps - translation rules - java code infix java inheritance red-black trees - workshop applet initialization lists priorityq workshop applet initializing arrays queue workshop applet inorder traversal (binary trees) separate chaining inorder(method sequential o...
23,268
iterators infixconverting to postfix - atend(method input classesmethods character interiterator java floating-point iterator class integers methods strings - operations library data structures references methodsmain() minimum spanning trees - minimum spanning trees for weighted graphs - new operator nodes java code tr...
23,269
key values hash java - insert(method key valuessorted lists keys binary trees double hashing linear searches big notation lines graphs hash functionsrandom keys link classdoubly linked lists hashing linked lists heap java keywords adjacency lists (graphs) binary trees private choosing public double-ended - knapsack pro...
23,270
references - towers java separate chaining tree java versus arrays tree java listings triangle java anagram java listinsertionsort java array java listiterator class binarysearch java lists brackets java adts doublylinked java sorted firstlastlist java efficiency hashchain java insertion sort - heap java java code - he...
23,271
main(method linklist java bubblesort() linkstack class change() lowarray class charat() lowarrayapp class compareto() postfixapp class delete(stack java higharray class manualsort(method linear probing mathematical induction (recursion) links maze analogy deques medianquicksort pivot value dfs() median-of-three partiti...
23,272
hashfunc () stackx class hashfunc () pop()stackx class heapify() preorder() incrementsize() priorityq class inorder() priorityqueue class insert(push()stackx class heaps putinpq() higharray class quicksort() linear probing readstring() priority queues recfind() queues recmergesort() insertafter() recquicksort() doubly ...
23,273
minimum spanning trees java code - mstw java finding efficiency modulo operator (%)hashing java code - moore' law workshop applet - mst(method mst java mstw(method mstw java heaps insertion - removal inserting java code - workshop applet key values -sorting - levels leaf navigating trees number required new button path...
23,274
quadratic probing hashdouble applet objects step accessing methods operators arrays assignment (=) classes dot ) comp to nodes equality (==) creating new sorting arrays java code overloaded lexicographical comparisons stability storing saving on stack ordarray class ordered arrays classdataarray java - advantages perso...
23,275
parsing arithmetic expressions parsing arithmetic expressions evaluating postfix - - popping parsing arithemetic expressions infix to postfix notation - - postal analogy (stacks) - stack workshop applet postfix notation postfix notation parseint(method evaluating - - partition java infixtranslating to postfix - - parti...
23,276
priorityq java priority queues priorityqueue classmethods workshop applet - private keywordbankaccount class quicksort procedural languages algorithm - modeling efficiency - organizational units (nsquaredperformance - problems partitioning programs partition algorithm - data storage structures partition java - dividing...
23,277
real-world data real-world data triangular numbers recfind(method efficiency recmergesort(method mathematical induction records methods -trees nth term with loop hashing nth term with recursion - memory blocks searching recquicksort(method rectriangle(methodstacktriangle java recursion triangle java - red-black trees t...
23,278
removalheap java - binaryguess- -number game remove(method external storagesearch criteria priority queues queues removingqueue workshop applet graphs breadth-first search - depth-first search - resources - indexing reverse java linear reverser class separate chaining rol buttonrbtree workshop sequential ordering - roo...
23,279
23,280
23,281
preface xv programminga general overview what' this book about mathematics review exponents logarithms series modular arithmetic the word brief introduction to recursion + classes basic class syntax extra constructor syntax and accessors separation of interface and implementation vector and string +details pointers lva...
23,282
contents big-five summary exercises references algorithm analysis mathematical background model what to analyze running-time calculations simple example general rules solutions for the maximum subsequence sum problem logarithms in the running time limitations of worst-case analysis summary exercises references listssta...
23,283
trees preliminaries implementation of trees tree traversals with an application binary trees implementation an exampleexpression trees the search tree adt--binary search trees contains findmin and findmax insert remove destructor and copy constructor average-case analysis avl trees single rotation double rotation splay...
23,284
contents hash tables with worst-case ( access perfect hashing cuckoo hashing hopscotch hashing universal hashing extendible hashing summary exercises references priority queues (heaps model simple implementations binary heap structure property heap-order property basic heap operations other heap operations applications...
23,285
shellsort worst-case analysis of shellsort heapsort analysis of heapsort mergesort analysis of mergesort quicksort picking the pivot partitioning strategy small arrays actual quicksort routines analysis of quicksort linear-expected-time algorithm for selection general lower bound for sorting decision trees decision-tre...
23,286
contents summary exercises references graph algorithms definitions representation of graphs topological sort shortest-path algorithms unweighted shortest paths dijkstra' algorithm graphs with negative edge costs acyclic graphs all-pairs shortest path shortest path example network flow problems simple maximum-flow algor...
23,287
the selection problem theoretical improvements for arithmetic problems dynamic programming using table instead of recursion ordering matrix multiplications optimal binary search tree all-pairs shortest path randomized algorithms random-number generators skip lists primality testing backtracking algorithms the turnpike ...
23,288
contents suffix arrays and suffix trees suffix arrays suffix trees linear-time construction of suffix arrays and suffix trees - trees pairing heaps summary exercises references appendix separate compilation of class templates everything in the header explicit instantiation index
23,289
purpose/goals the fourth edition of data structures and algorithm analysis in +describes data structuresmethods of organizing large amounts of dataand algorithm analysisthe estimation of the running time of algorithms as computers become faster and fasterthe need for programs that can handle large amounts of input beco...
23,290
preface difficult for readers to actually use the code as resultin this edition the online code represents class templates as single unitwith no separation of interface and implementation provides review of the +features that are used throughout the text and describes our approach to class templates appendix describes ...
23,291
covers listsstacksand queues this includes discussion of the stl vector and list classesincluding material on iteratorsand it provides implementations of significant subset of the stl vector and list classes covers treeswith an emphasis on search treesincluding external search trees ( -treesthe unix file system and exp...
23,292
preface is far too brief to be used in such course you might find it useful to use an additional work on np-completeness to augment this text exercises exercisesprovided at the end of each match the order in which material is presented the last exercises may address the as whole rather than specific section difficult e...
23,293
programminga general overview in this we discuss the aims and goals of this text and briefly review programming concepts and discrete mathematics we will see that how program performs for reasonably large input is just as important as its performance on moderate amounts of input summarize the basic mathematical backgro...
23,294
programminga general overview figure sample word puzzle because they are entirely impractical for input sizes that third algorithm can handle in reasonable amount of time second problem is to solve popular word puzzle the input consists of twodimensional array of letters and list of words the object is to find the word...
23,295
exponents xa xb xa+ xa xa- xb (xa ) xab xn xn xn  + logarithms in computer scienceall logarithms are to the base unless specified otherwise definition xa if and only if logx several convenient equalities follow from this definition theorem loga logc logc abc  proof let logc by logc aand loga thenby the definition of ...
23,296
programminga general overview series the easiest formulas to remember are + = and the companionn ai = an+ - in the latter formulaif then ai < = - and as tends to the sum approaches /( athese are the "geometric seriesformulas we can derive the last formula for = ( in the following manner let be the sum then then as if w...
23,297
another type of common series in analysis is the arithmetic series any such series can be evaluated from the basic formulan ii= ( for instanceto find the sum ( )rewrite it as ( ( )which is clearly ( )/ another way to remember this is to add the first and last terms (total )the second and next-to-last terms (total )and ...
23,298
programminga general overview oftenn is prime number in that casethere are three important theoremsfirstif is primethen ab (mod nis true if and only if (mod nor (mod nin other wordsif prime number divides product of two numbersit divides at least one of the two numbers secondif is primethen the equation ax (mod nhas un...
23,299
fk+ ( / / )( / ) + ( / )( / ) + ( / ) + proving the theorem as second examplewe establish the following theorem theorem if > then  = ( + )( + proof the proof is by induction for the basisit is readily seen that the theorem is true when for the inductive hypothesisassume that the theorem is true for < < we will establi...