SlideShare uma empresa Scribd logo
1 de 13
CHAPTER 7 Greedy Algorithms
Algorithm 7.1.1 Greedy Coin Changing This algorithm makes change for an amount  A  using coins of denominations denom [1] >  denom [2] > ··· >  denom [ n ] = 1. Input Parameters:  denom , A Output Parameters: None greedy_coin_change ( denom , A ) { i  = 1 while ( A  > 0) { c  =  A / denom [ i ] println (“use ” +  c  + “ coins of denomination ” +  denom [ i ]) A  =  A  -  c  *  denom [ i ] i  =  i  + 1 } }
Algorithm 7.2.4 Kruskal’s Algorithm Kruskal’s algorithm finds a minimal spanning tree in a connected, weighted graph with vertex set {1, ... ,  n } . The input to the algorithm is  edgelist , an array of  edge , and  n . The members of edge are •  v  and  w , the vertices on which the edge is incident. •  weight , the weight of the edge. The output lists the edges in a minimal spanning tree. The function  sort  sorts the array  edgelist  in nondecreasing order of weight.
Input Parameters:  edgelist , n Output Parameters: None kruskal ( edgelist , n ) { sort ( edgelist ) for  i  = 1 to  n makeset ( i ) count  = 0 i  = 1 while ( count  <  n  - 1) { if ( findset ( edgelist [ i ]. v ) !=  findset ( edgelist [ i ]. w )) { println ( edgelist [ i ]. v  + “ ”  +  edgelist [ i ]. w ) count  =  count  + 1 union ( edgelist [ i ]. v , edgelist [ i ]. w ) } i  =  i  + 1 } }
Algorithm 7.3.4 Prim’s Algorithm This algorithm finds a minimal spanning tree in a connected, weighted,  n -vertex graph. The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ver , the vertex adjacent to  i ;  weight , representing the weight of edge ( i , ver ); and  next , a reference to the next node in the linked list or null, for the last node in the linked list. The start vertex is  start . In the minimal spanning tree, the parent of vertex  i   ≠   start  is  parent [ i ], and  parent [ start ] = 0. The value  ∞  is the largest available integer value.
Input Parameters:  adj , start Output Parameters:  parent prim ( adj , start , parent ) { n  =  adj . last for  i  = 1 to  n key [ i ] = ∞  //  key  is a local array key [ start ] = 0 parent [ start ] = 0 // the following statement initializes the // container  h  to the values in the array  key h . init ( key , n ) for  i  = 1 to  n  { v  =  h . del () ref  =  adj [ v ] while ( ref  != null) { w  =  ref . ver if ( h . isin ( w ) &&  ref . weight  <  h . keyval ( w )) { parent [ w ] =  v h . decrease ( w , ref . weight ) } ref  =  ref . next } } }
Algorithm 7.4.4 Dijkstra’s Algorithm This algorithm finds shortest paths from the designated vertex  start  to all of the other vertices in a connected, weighted,  n -vertex graph. The graph is represented using adjacency lists;  adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex  i . Each node has members  ver , the vertex adjacent to  i ;  weight , representing the weight of edge ( i , ver ); and  next , a reference to the next node in the linked list or null, for the last node in the linked list. In a shortest path, the predecessor of vertex  i   start is  predecessor [ i ], and  predecessor [ star t]  = 0. The value  ∞  is the largest available integer value. The abstract data type  h  supports the same operations as in Prim’s algorithm.
Input Parameters:  adj , start Output Parameters:  parent dijkstra ( adj , start , parent ) { n  =  adj . last for  i  = 1 to  n key [ i ] = ∞  //  key  is a local array key [ start ] = 0 predecessor [ start ] = 0 ...
... // the following statement initializes the // container  h  to the values in the array  key h . init ( key , n ) for  i  = 1 to  n  { v  =  h . min_weight_index () min_cost  =  h . keyval ( v ) v  =  h . del () ref  =  adj [ v ] while ( ref  != null) { w  =  ref . ver if ( h . isin ( w ) &&  min_cost  +  ref . weight  <  h . keyval ( w )) { predecessor [ w ] =  v h . decrease ( w ,  min_cost + ref . weight ) } // end if ref  =  ref . next } // end while } // end for }
Algorithm 7.5.3 Huffman’s Algorithm This algorithm constructs an optimal Huffman coding tree. The input is an array  a  of  n  = 2 nodes. Each node has an integer member  character  to identify a particular character, another integer member  key  to identify that character’s frequency, and  left  and  right  members. After the Huffman coding tree is constructed, a left member of a node references its left child, and a right member of a node references its right child or, if the node is a terminal vertex, its left and right members are null. The algorithm returns a reference to the root of the Huffman coding tree. The operator, new, is used to obtain a new node. If  a  is an array, the expression h . init ( a ) initializes the container  h  to the data in  a . The expression h . del () deletes the node in  h  with the smallest key and returns the node. The expression h . insert ( ref  ) inserts the node referenced by  ref  into  h .
Input Parameters:  a Output Parameters: None huffman ( a ) { h . init ( a ) for  i  = 1 to  a . last  - 1 { ref  = new  node ref . left  =  h . del () ref . right  =  h . del () ref . key  =  ref . left . key  +  ref . right . key h . insert ( ref ) } return  h . del () }
Algorithm 7.6.2 Greedy Algorithm for the Continuous-Knapsack Problem The input to the algorithm is the knapsack capacity  C , and an array  a  of size  n , each of whose entries specifies an  id  (e.g., the first item might have  id  1, the second item might have  id  2, etc.), a profit  p , and a weight  w . The output tells how much of each object to select to maximize the profit. Objects not selected do not appear in the output. The function  sort  sorts the array  a  in nonincreasing order of the ratio of profit to weight.
Input Parameters:  a , C Output Parameters: None continuous_knapsack ( a , C )  { n  =  a . last for  i  = 1 to  n ratio [ i ] =  a [ i ]. p / a [ i ]. w sort ( a , ratio ) weight  = 0 i  = 1 while ( i  ≤  n  &&  weight  <  C )  { if ( weight  +  a [ i ]. w  =  C ) { println (“select all of object ” +  a [ i ]. id ) weight  =  weight  +  a [ i ]. w } else { r  = ( C  -  weight )/ a [ i ]. w println(“select ” + r + “ of object ” +  a [ i ]. id ) weight  =  C } i  =  i  + 1 } }

Mais conteúdo relacionado

Mais procurados

Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
Vikash Dhal
 

Mais procurados (19)

Lec1
Lec1Lec1
Lec1
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Numpy string functions
Numpy string functionsNumpy string functions
Numpy string functions
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Introducing Assignment invalidates the Substitution Model of Evaluation and v...
Introducing Assignment invalidates the Substitution Model of Evaluation and v...
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Greedy method by Dr. B. J. Mohite
Greedy method by Dr. B. J. MohiteGreedy method by Dr. B. J. Mohite
Greedy method by Dr. B. J. Mohite
 
Lec30
Lec30Lec30
Lec30
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Lec22
Lec22Lec22
Lec22
 
Strings
StringsStrings
Strings
 
Function
Function Function
Function
 
Recursive squaring
Recursive squaringRecursive squaring
Recursive squaring
 
C# Strings
C# StringsC# Strings
C# Strings
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
 

Destaque

Program Edukacyjny W Fabryce Emalii Oskara Schindlera
Program Edukacyjny W Fabryce Emalii Oskara SchindleraProgram Edukacyjny W Fabryce Emalii Oskara Schindlera
Program Edukacyjny W Fabryce Emalii Oskara Schindlera
guestbdec7c
 
Barrier of packaging
Barrier of packagingBarrier of packaging
Barrier of packaging
hoangvunl
 
電子書籍と図書館 120619Ver.3
電子書籍と図書館 120619Ver.3電子書籍と図書館 120619Ver.3
電子書籍と図書館 120619Ver.3
shinya Jingushi
 
Disco Dirt Evaluation
Disco Dirt EvaluationDisco Dirt Evaluation
Disco Dirt Evaluation
hanmat
 
(Application pdf object) 50 str
(Application pdf object) 50 str(Application pdf object) 50 str
(Application pdf object) 50 str
ABC
 
Nings To Knols Upload
Nings To Knols UploadNings To Knols Upload
Nings To Knols Upload
guesta3ed78
 

Destaque (20)

Haiti Slide Show1
Haiti Slide Show1Haiti Slide Show1
Haiti Slide Show1
 
Lecture7
Lecture7Lecture7
Lecture7
 
Program Edukacyjny W Fabryce Emalii Oskara Schindlera
Program Edukacyjny W Fabryce Emalii Oskara SchindleraProgram Edukacyjny W Fabryce Emalii Oskara Schindlera
Program Edukacyjny W Fabryce Emalii Oskara Schindlera
 
Profiting In A LinkedIn Economy
Profiting In A LinkedIn EconomyProfiting In A LinkedIn Economy
Profiting In A LinkedIn Economy
 
Barrier of packaging
Barrier of packagingBarrier of packaging
Barrier of packaging
 
Natura2000 V2 En
Natura2000 V2 EnNatura2000 V2 En
Natura2000 V2 En
 
電子書籍と図書館 120619Ver.3
電子書籍と図書館 120619Ver.3電子書籍と図書館 120619Ver.3
電子書籍と図書館 120619Ver.3
 
Json JavaScript Object Notation
Json JavaScript Object NotationJson JavaScript Object Notation
Json JavaScript Object Notation
 
Don't Screw Up Your Licensing
Don't Screw Up Your LicensingDon't Screw Up Your Licensing
Don't Screw Up Your Licensing
 
Protsesor
ProtsesorProtsesor
Protsesor
 
Cei week 1
Cei week 1Cei week 1
Cei week 1
 
Disco Dirt Evaluation
Disco Dirt EvaluationDisco Dirt Evaluation
Disco Dirt Evaluation
 
Chap02alg
Chap02algChap02alg
Chap02alg
 
Python
PythonPython
Python
 
2010 Training And Educational Offerings For Northern Ohio’S
2010 Training And Educational Offerings For Northern Ohio’S2010 Training And Educational Offerings For Northern Ohio’S
2010 Training And Educational Offerings For Northern Ohio’S
 
Chap08alg
Chap08algChap08alg
Chap08alg
 
(Application pdf object) 50 str
(Application pdf object) 50 str(Application pdf object) 50 str
(Application pdf object) 50 str
 
IP Basics
IP BasicsIP Basics
IP Basics
 
Lecture8
Lecture8Lecture8
Lecture8
 
Nings To Knols Upload
Nings To Knols UploadNings To Knols Upload
Nings To Knols Upload
 

Semelhante a Chap07alg

In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
stopgolook
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
info673628
 

Semelhante a Chap07alg (20)

Chap12alg
Chap12algChap12alg
Chap12alg
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Write a program that reads a connected graph from a file and displays.docx
 Write a program that reads a connected graph from a file and displays.docx Write a program that reads a connected graph from a file and displays.docx
Write a program that reads a connected graph from a file and displays.docx
 
Cs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer keyCs6402 design and analysis of algorithms may june 2016 answer key
Cs6402 design and analysis of algorithms may june 2016 answer key
 
Chap04alg
Chap04algChap04alg
Chap04alg
 
Chap04alg
Chap04algChap04alg
Chap04alg
 
Ada notes
Ada notesAda notes
Ada notes
 
Array
ArrayArray
Array
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Chp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdfChp-1 Quick Review of basic concepts.pdf
Chp-1 Quick Review of basic concepts.pdf
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
ARRAY in python and c with examples .pptx
ARRAY  in python and c with examples .pptxARRAY  in python and c with examples .pptx
ARRAY in python and c with examples .pptx
 
Chap08alg
Chap08algChap08alg
Chap08alg
 
Below is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdfBelow is the assignment description and the file I have written..pdf
Below is the assignment description and the file I have written..pdf
 
Merge radix-sort-algorithm
Merge radix-sort-algorithmMerge radix-sort-algorithm
Merge radix-sort-algorithm
 

Mais de Munhchimeg (20)

Ded algorithm1
Ded algorithm1Ded algorithm1
Ded algorithm1
 
Ded algorithm
Ded algorithmDed algorithm
Ded algorithm
 
Tobch lecture1
Tobch lecture1Tobch lecture1
Tobch lecture1
 
Tobch lecture
Tobch lectureTobch lecture
Tobch lecture
 
Recursive
RecursiveRecursive
Recursive
 
Lecture916
Lecture916Lecture916
Lecture916
 
Lecture915
Lecture915Lecture915
Lecture915
 
Lecture914
Lecture914Lecture914
Lecture914
 
Lecture913
Lecture913Lecture913
Lecture913
 
Lecture912
Lecture912Lecture912
Lecture912
 
Lecture911
Lecture911Lecture911
Lecture911
 
Lecture910
Lecture910Lecture910
Lecture910
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture8
Lecture8Lecture8
Lecture8
 
Lecture7
Lecture7Lecture7
Lecture7
 
Lecture6
Lecture6Lecture6
Lecture6
 
Lecture5
Lecture5Lecture5
Lecture5
 
Lecture4
Lecture4Lecture4
Lecture4
 
Lecture3
Lecture3Lecture3
Lecture3
 
Protsesor
ProtsesorProtsesor
Protsesor
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Chap07alg

  • 1. CHAPTER 7 Greedy Algorithms
  • 2. Algorithm 7.1.1 Greedy Coin Changing This algorithm makes change for an amount A using coins of denominations denom [1] > denom [2] > ··· > denom [ n ] = 1. Input Parameters: denom , A Output Parameters: None greedy_coin_change ( denom , A ) { i = 1 while ( A > 0) { c = A / denom [ i ] println (“use ” + c + “ coins of denomination ” + denom [ i ]) A = A - c * denom [ i ] i = i + 1 } }
  • 3. Algorithm 7.2.4 Kruskal’s Algorithm Kruskal’s algorithm finds a minimal spanning tree in a connected, weighted graph with vertex set {1, ... , n } . The input to the algorithm is edgelist , an array of edge , and n . The members of edge are • v and w , the vertices on which the edge is incident. • weight , the weight of the edge. The output lists the edges in a minimal spanning tree. The function sort sorts the array edgelist in nondecreasing order of weight.
  • 4. Input Parameters: edgelist , n Output Parameters: None kruskal ( edgelist , n ) { sort ( edgelist ) for i = 1 to n makeset ( i ) count = 0 i = 1 while ( count < n - 1) { if ( findset ( edgelist [ i ]. v ) != findset ( edgelist [ i ]. w )) { println ( edgelist [ i ]. v + “ ” + edgelist [ i ]. w ) count = count + 1 union ( edgelist [ i ]. v , edgelist [ i ]. w ) } i = i + 1 } }
  • 5. Algorithm 7.3.4 Prim’s Algorithm This algorithm finds a minimal spanning tree in a connected, weighted, n -vertex graph. The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ver , the vertex adjacent to i ; weight , representing the weight of edge ( i , ver ); and next , a reference to the next node in the linked list or null, for the last node in the linked list. The start vertex is start . In the minimal spanning tree, the parent of vertex i ≠ start is parent [ i ], and parent [ start ] = 0. The value ∞ is the largest available integer value.
  • 6. Input Parameters: adj , start Output Parameters: parent prim ( adj , start , parent ) { n = adj . last for i = 1 to n key [ i ] = ∞ // key is a local array key [ start ] = 0 parent [ start ] = 0 // the following statement initializes the // container h to the values in the array key h . init ( key , n ) for i = 1 to n { v = h . del () ref = adj [ v ] while ( ref != null) { w = ref . ver if ( h . isin ( w ) && ref . weight < h . keyval ( w )) { parent [ w ] = v h . decrease ( w , ref . weight ) } ref = ref . next } } }
  • 7. Algorithm 7.4.4 Dijkstra’s Algorithm This algorithm finds shortest paths from the designated vertex start to all of the other vertices in a connected, weighted, n -vertex graph. The graph is represented using adjacency lists; adj [ i ] is a reference to the first node in a linked list of nodes representing the vertices adjacent to vertex i . Each node has members ver , the vertex adjacent to i ; weight , representing the weight of edge ( i , ver ); and next , a reference to the next node in the linked list or null, for the last node in the linked list. In a shortest path, the predecessor of vertex i start is predecessor [ i ], and predecessor [ star t] = 0. The value ∞ is the largest available integer value. The abstract data type h supports the same operations as in Prim’s algorithm.
  • 8. Input Parameters: adj , start Output Parameters: parent dijkstra ( adj , start , parent ) { n = adj . last for i = 1 to n key [ i ] = ∞ // key is a local array key [ start ] = 0 predecessor [ start ] = 0 ...
  • 9. ... // the following statement initializes the // container h to the values in the array key h . init ( key , n ) for i = 1 to n { v = h . min_weight_index () min_cost = h . keyval ( v ) v = h . del () ref = adj [ v ] while ( ref != null) { w = ref . ver if ( h . isin ( w ) && min_cost + ref . weight < h . keyval ( w )) { predecessor [ w ] = v h . decrease ( w , min_cost + ref . weight ) } // end if ref = ref . next } // end while } // end for }
  • 10. Algorithm 7.5.3 Huffman’s Algorithm This algorithm constructs an optimal Huffman coding tree. The input is an array a of n = 2 nodes. Each node has an integer member character to identify a particular character, another integer member key to identify that character’s frequency, and left and right members. After the Huffman coding tree is constructed, a left member of a node references its left child, and a right member of a node references its right child or, if the node is a terminal vertex, its left and right members are null. The algorithm returns a reference to the root of the Huffman coding tree. The operator, new, is used to obtain a new node. If a is an array, the expression h . init ( a ) initializes the container h to the data in a . The expression h . del () deletes the node in h with the smallest key and returns the node. The expression h . insert ( ref ) inserts the node referenced by ref into h .
  • 11. Input Parameters: a Output Parameters: None huffman ( a ) { h . init ( a ) for i = 1 to a . last - 1 { ref = new node ref . left = h . del () ref . right = h . del () ref . key = ref . left . key + ref . right . key h . insert ( ref ) } return h . del () }
  • 12. Algorithm 7.6.2 Greedy Algorithm for the Continuous-Knapsack Problem The input to the algorithm is the knapsack capacity C , and an array a of size n , each of whose entries specifies an id (e.g., the first item might have id 1, the second item might have id 2, etc.), a profit p , and a weight w . The output tells how much of each object to select to maximize the profit. Objects not selected do not appear in the output. The function sort sorts the array a in nonincreasing order of the ratio of profit to weight.
  • 13. Input Parameters: a , C Output Parameters: None continuous_knapsack ( a , C ) { n = a . last for i = 1 to n ratio [ i ] = a [ i ]. p / a [ i ]. w sort ( a , ratio ) weight = 0 i = 1 while ( i ≤ n && weight < C ) { if ( weight + a [ i ]. w = C ) { println (“select all of object ” + a [ i ]. id ) weight = weight + a [ i ]. w } else { r = ( C - weight )/ a [ i ]. w println(“select ” + r + “ of object ” + a [ i ]. id ) weight = C } i = i + 1 } }