SlideShare uma empresa Scribd logo
1 de 21
CHAPTER 8 Dynamic Programming
Algorithm 8.1.1 Computing the Fibonacci Numbers, Version 1 This dynamic-programming algorithm computes the Fibonacci number  f [ n ]. It uses the formulas f [1] = 1;  f [2] = 1;  f [ n ] =  f [ n  - 1] +  f [ n  - 2],  n   ≥  3. At the conclusion of the algorithm, the array  f  holds the first  n  Fibonacci numbers. Input Parameters:  n Output Parameters: None fibonacci1 ( n ) { //  f  is a local array f [1] = 1 f [2] = 1 for  i  = 3 to  n f [ i ] =  f [ i  - 1] +  f [ i  - 2] return  f [ n ] }
Algorithm 8.1.1 Computing the Fibonacci Numbers, Version 2 This dynamic-programming algorithm computes the Fibonacci number  f n  . It uses the formulas  f 1  = 1;  f 2  = 1;  f n  =  f n  - 1  +  f n  - 2 ,  n   ≥  3. It saves the two preceding Fibonacci numbers in the variables  f_twoback  and  f_oneback   in order to compute the next Fibonacci number. Input Parameters:  n Output Parameters: None fibonacci2 ( n ) { if ( n  == 1 ||  n  == 2) return 1 f_twoback  = 1 f_oneback  = 1 for  i  = 3 to  n  { f  =  f_twoback  +  f_oneback f_twoback  =  f_oneback f_oneback  =  f } return  f }
Computing the Fibonacci Numbers Recursively This algorithm computes the Fibonacci number  f n  recursively using the formulas  f 1  = 1;  f 2  = 1;  f n  =  f n  - 1  +  f n  - 2 ,  n   ≥  3. Input Parameters:  n Output Parameters: None fibonacci_recurs ( n ) { if ( n  == 1) return 1 if ( n  == 2) return 1 return  fibonacci_recurs ( n  - 2) +  fibonacci_recurs ( n  - 1) }
Computing the Fibonacci Numbers with Memoization This algorithm computes the Fibonacci number  f n  recursively (with memoization) using the formulas  f 1  = 1;  f 2  = 1;  f n  =  f n  - 1  +  f n  - 2 ,  n   ≥  3.
Input Parameters:  n Output Parameters: None memoized_fibonacci ( n ) { for  i  = 1 to  n results [ i ] = -1 // -1 means undefined return  memoized_fibonacci_recurs ( results , n ) } memoized_fibonacci_recurs ( results , n ) { if ( results [ n ] != -1) return  results [ n ] if ( n  == 1) val  = 1 else if ( n  == 2) val  = 1 else { val  =  memoized_fibonacci_recurs ( results , n  - 2) val  =  val  +  memoized_fibonacci_recurs ( results , n  - 1) } results [ n ] =  val return  val }
Algorithm 8.2.1 Coin Changing Using Dynamic Programming, Version 1 This dynamic-programming algorithm computes the minimum number of coins to make change for a given amount. The input is an array  denom  that specifies the denominations of the coins, denom [1] >  denom [2] > ··· >  denom [ n ] = 1, and an amount  A . The output is an array  C  whose value,  C [ i ][ j ], is the minimum number of coins to make change for the amount  j , using coins  i through  n , 1  ≤  i  ≤  n, 0  ≤  j  ≤  A.
Input Parameters:  denoma , A Output Parameters: None dynamic_coin_change1 ( denom , A , C ) { n  =  denom . last for  j  = 0 to  A C [ n ][ j ] =  j for  i  =  n  - 1 downto 1 for  j  = 0 to  A if ( denom [ i ] >  j  ||  C [ i  + 1][ j ] < 1 +  C [ i ][ j  -  denom [ i ]]) C [ i ][ j ] =  C [ i  + 1][ j ] else C [ i ][ j ] = 1 +  C [ i ][ j  -  denom [ i ]] }
Algorithm 8.2.2 Coin Changing Using Dynamic Programming, Version 2 This dynamic-programming algorithm computes the minimum number of coins to make change for a given amount and tracks which coins are used. The input is an array  denom  that specifies the denominations of the coins, denom [1] >  denom [2] > ··· >  denom [ n ] = 1, and an amount  A . The output consists of arrays  C  and  used . The value,  C [ i ][ j ], is the minimum number of coins to make change for the amount  j , using coins  I  through  n , 1  ≤  i  ≤  n, 0  ≤  j  ≤  A. The value,  used [ i ][ j ], is true or false to signify whether coin  i  appears in the smallest set of coins computed by Algorithm 8.2.1 for the amount  j  using only coins  i  through  n . The values of  i  and  j  satisfy 1  ≤  i  ≤  n, 0  ≤  j  ≤  A.
Input Parameters:  denom , A Output Parameters:  C , used dynamic_coin_change2 ( denom , A , C , used ) { n  =  denom . last for  j  = 0 to  A  { C [ n ][ j ] =  j used [ n ][ j ] = true } for  i  =  n  - 1 downto 1 for  j  = 0 to  A if ( denom [ i ] >  j  ||  C [ i  + 1][ j ] < 1 +  C [ i ][ j  -  denom [ i ]]) C [ i ][ j ] =  C [ i  + 1][ j ] used[ i ][ j ] = false else C [ i ][ j ] = 1 +  C [ i ][ j  -  denom [ i ]] used[ i ][ j ] = true } }
Algorithm 8.2.4 Computing a Minimum- Size Set of Coins for a Given Amount This algorithm outputs a minimum-size set of coins to make change for an amount  j  using any of coins  i  through  n  with denominations specified by Algorithm 8.2.2. The algorithm inputs the index  i , the amount  j , the array  denom  of Algorithm 8.2.2, and the array  used  computed by Algorithm 8.2.2.
Input Parameters:  i , j , denom , used Output Parameters: None optimal_coins_set ( i , j , denom , used ) { if ( j  == 0) return if ( used [ i ][ j ]) { println (“Use a coin of denomination ” +  denom [ i ]) optimal_coins_set ( i , j  -  denom [ i ], denom , used ) } else optimal_coins_set ( i  + 1, j , denom , used ) }
Algorithm 8.3.1 Optimal Matrix Multiplication This algorithm computes the minimum number of scalar multiplications to multiply a sequence of  n  matrices. The input is the array  size  that contains the sizes of the matrices to be multiplied. The first matrix is  size [0] ×  size [1]; the second is  size [1] ×  size [2]; and so on. The  n th matrix is  size [ n  - 1] ×  size [ n ]. The output is the array  s  whose value,  s [ i ][ j ], is the minimum number of scalar multiplications to multiply matrices  i  through  j . The value  ∞  is the largest available integer value.
Input Parameters:  size Output Parameters:  s opt_matrix_mult ( size , s ) { n  =  size . last for  i  = 1 to  n s [ i ][ i ] = 0 //  w  =  j  -  i for  w  = 1 to  n  - 1 for  i  = 1 to  n  -  w  { j  =  w  +  i s [ i ][ j ] = ∞ for  k  =  i  to  j  - 1 { q  =  s [ i ][ k ] +  s [ k  + 1][ j ] +  size [ i  - 1] *  size [ k ] *  size [ j ] if ( q  <  s [ i ][ j ]) s [ i ][ j ] =  q } } }
Algorithm 8.4.2 Computing the Length of a Longest Common Subsequence This dynamic-programming algorithm computes the length  c [ i ][ j ] of a longest common subsequence of  a [1], ... , a[ i ]  and  b [1], ... ,  b [ j ]  for  i  = 0, ... ,  m  and  j  = 0, ... ,  n . Input Parameters:  a , b Output Parameters:  c LCS ( a , b , c ) { m  =  a . last n  =  b . last for  i  = 0 to  m c [ i ][0] = 0 for  j  = 1 to  n c[0][ j ] = 0 for  i  = 1 to  m for  j  = 1 to  n if ( a [ i ] !=  b [ j ]) c [ i ][ j ] =  max ( c [ i  - 1][ j ], c [ i ][ j  - 1]) else c [ i ][ j ] = 1 +  c [ i  - 1][ j  - 1] }
Algorithm 8.4.3 Computing a Longest Common Subsequence This algorithm uses the array  c  computed by Algorithm 8.4.2 to output a longest common subsequence. The array  a  of length  m  is the first sequence input to Algorithm 8.4.2, and  n  is the length of the second sequence input to Algorithm 8.4.2. Input Parameters:  a , m  (length of  a ), n  (length of second sequence), c  (contains lengths of longest common subsequences) Output Parameters: None LCS_print ( a , m , n , c ) { if ( c [ m ][ n ] == 0) return if ( c [ m ][ n ] ==  c [ m  - 1][ n ]) LCS_print ( a , m  - 1, n , c ) else if ( c [ m ][ n ] ==  c [ m ][ n  - 1]) LCS_print ( a , m , n  - 1, c ) else { LCS_print ( a , m  - 1, n  - 1, c ) print ( a [ m ]) } }
Algorithm 8.5.3 Floyd’s Algorithm, Version 1 This algorithm computes the length of a shortest path between each pair of vertices in a simple, undirected, weighted graph  G . All weights are nonnegative. The input is the adjacency matrix  A  of  G . The output is the matrix  A  whose  ij th entry is the length of a shortest path from vertex  i  to vertex  j . Input Parameter:  A Output Parameter:  A all_paths ( A ) { n  =  A . last for  k  = 1 to  n  // compute  A ( k ) for  i  = 1 to  n for  j  = 1 to  n if ( A [ i ][ k ] +  A [ k ][ j ] <  A [ i ][ j ]) A [ i ][ j ] =  A [ i ][ k ] +  A [ k ][ j ] }
Algorithm 8.5.4 Floyd’s Algorithm, Version 2 This algorithm computes the length of a shortest path between each pair of vertices in a simple, undirected, weighted graph  G  and stores the vertex that follows the first vertex on each shortest path. All weights are nonnegative. The input is the adjacency matrix  A  of  G . The output is the matrix  A  whose  ij th entry is the length of a shortest path from vertex  i  to vertex  j  and the matrix  next  whose  ij th entry is the vertex that follows  i  on a shortest path from  i  to  j .
Input Parameter:  A Output Parameter:  A , next all_paths ( A , next ) { n  =  A . last // initialize next: if no intermediate // vertices are allowed  next [ i ][ j ] =  j for  i  = 1 to  n for  j  = 1 to  n next [ i ][ j ] =  j for  k  = 1 to  n  // compute  A ( k ) for  i  = 1 to  n for  j  = 1 to  n if ( A [ i ][ k ] +  A [ k ][ j ] <  A [ i ][ j ]) { A [ i ][ j ] =  A [ i ][ k ] +  A [ k ][ j ] next [ i ][ j ] =  next [ i ][ k ] } }
Algorithm 8.5.5 Finding a Shortest Path This algorithm outputs a shortest path from vertex  i  to vertex  j  in a simple, undirected, weighted graph  G . It assumes that matrix  next  has already been computed by Algorithm 8.5.4. Input Parameters:  next , i , j Output Parameters: None print_path ( next , i , j ) { // if no intermediate vertices, just  // print  i  and  j  and return if ( j  ==  next [ i ][ j ]) { print ( i  + “ ” +  j ) return } // output  i  and then the path from the vertex // after  i  ( next [ i ][ j ]) to  j print ( i  + “ ”) print_path ( next , next [ i ][ j ], j ) }
Algorithm 8.5.12 Warshall’s Algorithm This algorithm computes the transitive closure of a relation  R  on {1, ... ,  n }. The input is the matrix  A  of  R . The output is the matrix  A  of the transitive closure of  R . Input Parameters:  A Output Parameters:  A transitive_closure ( A ) { n  =  A . last for  k  = 1 to  n   for  i  = 1 to  n for  j  = 1 to  n A [ i ][ j ] =  A [ i ][ j ]    ( A [ i ][ k ]     A [ k ][ j ]) }

Mais conteúdo relacionado

Mais procurados

dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)Mumtaz Ali
 
Data Structure Insertion sort
Data Structure Insertion sort Data Structure Insertion sort
Data Structure Insertion sort Mahesh Dheravath
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingJay Nagar
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosluzenith_g
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cppAlamgir Hossain
 
Computer graphics
Computer graphics Computer graphics
Computer graphics shafiq sangi
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1debolina13
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)JAINAM KAPADIYA
 
Engineering ppt by venay magen
Engineering ppt by venay magenEngineering ppt by venay magen
Engineering ppt by venay magenvenaymagen19
 
Circular convolution Using DFT Matlab Code
Circular convolution Using DFT Matlab CodeCircular convolution Using DFT Matlab Code
Circular convolution Using DFT Matlab CodeBharti Airtel Ltd.
 

Mais procurados (20)

Dynamicpgmming
DynamicpgmmingDynamicpgmming
Dynamicpgmming
 
Dynamic programming Basics
Dynamic programming BasicsDynamic programming Basics
Dynamic programming Basics
 
dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)dynamic programming complete by Mumtaz Ali (03154103173)
dynamic programming complete by Mumtaz Ali (03154103173)
 
Data Structure Insertion sort
Data Structure Insertion sort Data Structure Insertion sort
Data Structure Insertion sort
 
Alg1
Alg1Alg1
Alg1
 
Cg lab cse-v (1) (1)
Cg lab cse-v (1) (1)Cg lab cse-v (1) (1)
Cg lab cse-v (1) (1)
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Introducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmosIntroducción al Análisis y diseño de algoritmos
Introducción al Análisis y diseño de algoritmos
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
algorithm Unit 5
algorithm Unit 5 algorithm Unit 5
algorithm Unit 5
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cpp
 
Computer graphics
Computer graphics   Computer graphics
Computer graphics
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1
 
algorithm Unit 3
algorithm Unit 3algorithm Unit 3
algorithm Unit 3
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
 
Engineering ppt by venay magen
Engineering ppt by venay magenEngineering ppt by venay magen
Engineering ppt by venay magen
 
Circular convolution Using DFT Matlab Code
Circular convolution Using DFT Matlab CodeCircular convolution Using DFT Matlab Code
Circular convolution Using DFT Matlab Code
 
Computer graphics 2
Computer graphics 2Computer graphics 2
Computer graphics 2
 
algorithm Unit 4
algorithm Unit 4 algorithm Unit 4
algorithm Unit 4
 

Destaque

Gagasan perda perlindungan anak kota bandung, juli 2011
Gagasan perda perlindungan anak kota bandung, juli 2011Gagasan perda perlindungan anak kota bandung, juli 2011
Gagasan perda perlindungan anak kota bandung, juli 2011Zamzam Muzaki Sm
 
データ集 トマ・ピケティ『21 世紀の資本』
データ集 トマ・ピケティ『21 世紀の資本』データ集 トマ・ピケティ『21 世紀の資本』
データ集 トマ・ピケティ『21 世紀の資本』shinya Jingushi
 
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...Ansel Halliburton
 
Alliantiefabriek Noord Holland Duurzame Projecten
Alliantiefabriek Noord Holland Duurzame ProjectenAlliantiefabriek Noord Holland Duurzame Projecten
Alliantiefabriek Noord Holland Duurzame ProjectenJohan Stuiver
 
Nings To Knols Upload
Nings To Knols UploadNings To Knols Upload
Nings To Knols Uploadguesta3ed78
 
CUEB Presentation
CUEB PresentationCUEB Presentation
CUEB Presentationbrianlynch
 
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 Schindleraguestbdec7c
 
Emi and emc
Emi and emcEmi and emc
Emi and emcashmad
 
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’Srobertsmech
 
Metallised films
Metallised filmsMetallised films
Metallised filmshoangvunl
 
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbesteden
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbestedenBerenschot presentatie Metaalunie Noord NL Samenwerken & aanbesteden
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbestedenJohan Stuiver
 
Berenschot persetatie Succesvol Aanbesteden 051010
Berenschot persetatie Succesvol Aanbesteden 051010Berenschot persetatie Succesvol Aanbesteden 051010
Berenschot persetatie Succesvol Aanbesteden 051010Johan Stuiver
 
Hybrid worlds - Fungi Progression - crews
Hybrid worlds -  Fungi Progression - crewsHybrid worlds -  Fungi Progression - crews
Hybrid worlds - Fungi Progression - crewsrv media
 
Pm104 2004 2005
Pm104 2004 2005Pm104 2004 2005
Pm104 2004 2005Munhchimeg
 

Destaque (20)

Gagasan perda perlindungan anak kota bandung, juli 2011
Gagasan perda perlindungan anak kota bandung, juli 2011Gagasan perda perlindungan anak kota bandung, juli 2011
Gagasan perda perlindungan anak kota bandung, juli 2011
 
データ集 トマ・ピケティ『21 世紀の資本』
データ集 トマ・ピケティ『21 世紀の資本』データ集 トマ・ピケティ『21 世紀の資本』
データ集 トマ・ピケティ『21 世紀の資本』
 
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...
Pirates v. Mercenaries: Purely Private Transnational Violence at the Margins ...
 
Alliantiefabriek Noord Holland Duurzame Projecten
Alliantiefabriek Noord Holland Duurzame ProjectenAlliantiefabriek Noord Holland Duurzame Projecten
Alliantiefabriek Noord Holland Duurzame Projecten
 
Nings To Knols Upload
Nings To Knols UploadNings To Knols Upload
Nings To Knols Upload
 
CUEB Presentation
CUEB PresentationCUEB Presentation
CUEB Presentation
 
Lecture916
Lecture916Lecture916
Lecture916
 
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
 
Emi and emc
Emi and emcEmi and emc
Emi and emc
 
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
 
Metallised films
Metallised filmsMetallised films
Metallised films
 
Resume
ResumeResume
Resume
 
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbesteden
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbestedenBerenschot presentatie Metaalunie Noord NL Samenwerken & aanbesteden
Berenschot presentatie Metaalunie Noord NL Samenwerken & aanbesteden
 
TLF Reunion 2011
TLF Reunion 2011TLF Reunion 2011
TLF Reunion 2011
 
Berenschot persetatie Succesvol Aanbesteden 051010
Berenschot persetatie Succesvol Aanbesteden 051010Berenschot persetatie Succesvol Aanbesteden 051010
Berenschot persetatie Succesvol Aanbesteden 051010
 
Hybrid worlds - Fungi Progression - crews
Hybrid worlds -  Fungi Progression - crewsHybrid worlds -  Fungi Progression - crews
Hybrid worlds - Fungi Progression - crews
 
Lecture913
Lecture913Lecture913
Lecture913
 
Lecture3
Lecture3Lecture3
Lecture3
 
Pm104 2004 2005
Pm104 2004 2005Pm104 2004 2005
Pm104 2004 2005
 
Chap07alg
Chap07algChap07alg
Chap07alg
 

Semelhante a DP Algorithms for Fibonacci, Coin Change, LCS & Shortest Paths

Advanced Datastructures and algorithms CP4151unit1b.pdf
Advanced Datastructures and algorithms CP4151unit1b.pdfAdvanced Datastructures and algorithms CP4151unit1b.pdf
Advanced Datastructures and algorithms CP4151unit1b.pdfSheba41
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptxKokilaK25
 
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAScientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAAhmed Gamal Abdel Gawad
 
Cgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckCgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckaiQUANT
 
A Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in MatlabA Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in MatlabaiQUANT
 
Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Alamgir Hossain
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 
Problem descriptionThe Jim Thornton Coffee House chain is .docx
Problem descriptionThe Jim Thornton Coffee House chain is .docxProblem descriptionThe Jim Thornton Coffee House chain is .docx
Problem descriptionThe Jim Thornton Coffee House chain is .docxelishaoatway
 

Semelhante a DP Algorithms for Fibonacci, Coin Change, LCS & Shortest Paths (20)

Chap12alg
Chap12algChap12alg
Chap12alg
 
Chap12alg
Chap12algChap12alg
Chap12alg
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Chap05alg
Chap05algChap05alg
Chap05alg
 
Chap06alg
Chap06algChap06alg
Chap06alg
 
Chap06alg
Chap06algChap06alg
Chap06alg
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Advanced Datastructures and algorithms CP4151unit1b.pdf
Advanced Datastructures and algorithms CP4151unit1b.pdfAdvanced Datastructures and algorithms CP4151unit1b.pdf
Advanced Datastructures and algorithms CP4151unit1b.pdf
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
 
Annotations.pdf
Annotations.pdfAnnotations.pdf
Annotations.pdf
 
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGAScientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
Scientific Computing II Numerical Tools & Algorithms - CEI40 - AGA
 
Cgo2007 P3 3 Birkbeck
Cgo2007 P3 3 BirkbeckCgo2007 P3 3 Birkbeck
Cgo2007 P3 3 Birkbeck
 
A Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in MatlabA Dimension Abstraction Approach to Vectorization in Matlab
A Dimension Abstraction Approach to Vectorization in Matlab
 
Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report Digital signal Processing all matlab code with Lab report
Digital signal Processing all matlab code with Lab report
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
Slide2
Slide2Slide2
Slide2
 
Problem descriptionThe Jim Thornton Coffee House chain is .docx
Problem descriptionThe Jim Thornton Coffee House chain is .docxProblem descriptionThe Jim Thornton Coffee House chain is .docx
Problem descriptionThe Jim Thornton Coffee House chain is .docx
 
Software Metrics
Software MetricsSoftware Metrics
Software Metrics
 
2_1 Edit Distance.pptx
2_1 Edit Distance.pptx2_1 Edit Distance.pptx
2_1 Edit Distance.pptx
 

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
 
Protsesor
ProtsesorProtsesor
Protsesor
 
Lecture916
Lecture916Lecture916
Lecture916
 
Lecture915
Lecture915Lecture915
Lecture915
 
Lecture914
Lecture914Lecture914
Lecture914
 
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
 
Protsesor
ProtsesorProtsesor
Protsesor
 
Pm104 standard
Pm104 standardPm104 standard
Pm104 standard
 

Último

2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914Delhi Call girls
 
Almora call girls 📞 8617697112 At Low Cost Cash Payment Booking
Almora call girls 📞 8617697112 At Low Cost Cash Payment BookingAlmora call girls 📞 8617697112 At Low Cost Cash Payment Booking
Almora call girls 📞 8617697112 At Low Cost Cash Payment BookingNitya salvi
 
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...ritikasharma
 
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...anamikaraghav4
 
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Serviceanamikaraghav4
 
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Riya Pathan
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...rahim quresi
 
Call Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersCall Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersanamikaraghav4
 
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser... Shivani Pandey
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...aamir
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...noor ahmed
 
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...rahim quresi
 
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034 Independent Chenna...
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034  Independent Chenna...Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034  Independent Chenna...
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034 Independent Chenna... Shivani Pandey
 

Último (20)

2k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 92055419142k Shot Call girls Laxmi Nagar Delhi 9205541914
2k Shot Call girls Laxmi Nagar Delhi 9205541914
 
Almora call girls 📞 8617697112 At Low Cost Cash Payment Booking
Almora call girls 📞 8617697112 At Low Cost Cash Payment BookingAlmora call girls 📞 8617697112 At Low Cost Cash Payment Booking
Almora call girls 📞 8617697112 At Low Cost Cash Payment Booking
 
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
Book Sex Workers Available Kolkata Call Girls Service Airport Kolkata ✔ 62971...
 
Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171Call Girls South Avenue Delhi WhatsApp Number 9711199171
Call Girls South Avenue Delhi WhatsApp Number 9711199171
 
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...
College Call Girls New Alipore - For 7001035870 Cheap & Best with original Ph...
 
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service👙  Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
👙 Kolkata Call Girls Park Circus 💫💫7001035870 Model escorts Service
 
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
Independent Hatiara Escorts ✔ 9332606886✔ Full Night With Room Online Booking...
 
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur EscortsVIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
VIP Call Girls Nagpur Megha Call 7001035870 Meet With Nagpur Escorts
 
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
 
Call Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbersCall Girl Service Belur - 7001035870 with real photos and phone numbers
Call Girl Service Belur - 7001035870 with real photos and phone numbers
 
Goa Call "Girls Service 9316020077 Call "Girls in Goa
Goa Call "Girls  Service   9316020077 Call "Girls in GoaGoa Call "Girls  Service   9316020077 Call "Girls in Goa
Goa Call "Girls Service 9316020077 Call "Girls in Goa
 
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Surajpur Greater Noida ✔️☆9289244007✔️☆ Female E...
 
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Velappanchavadi WhatsApp Booking 7427069034 call girl ser...
 
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Rajpur ⟟ 8250192130 ⟟ High Class Call Girl In...
 
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
Call Girls Chirag Delhi Delhi WhatsApp Number 9711199171
 
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
Dakshineswar Call Girls ✔ 8005736733 ✔ Hot Model With Sexy Bhabi Ready For Se...
 
Desi Bhabhi Call Girls In Goa 💃 730 02 72 001💃desi Bhabhi Escort Goa
Desi Bhabhi Call Girls  In Goa  💃 730 02 72 001💃desi Bhabhi Escort GoaDesi Bhabhi Call Girls  In Goa  💃 730 02 72 001💃desi Bhabhi Escort Goa
Desi Bhabhi Call Girls In Goa 💃 730 02 72 001💃desi Bhabhi Escort Goa
 
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
↑Top Model (Kolkata) Call Girls Behala ⟟ 8250192130 ⟟ High Class Call Girl In...
 
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
 
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034 Independent Chenna...
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034  Independent Chenna...Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034  Independent Chenna...
Verified Trusted Call Girls Tambaram Chennai ✔✔7427069034 Independent Chenna...
 

DP Algorithms for Fibonacci, Coin Change, LCS & Shortest Paths

  • 1. CHAPTER 8 Dynamic Programming
  • 2. Algorithm 8.1.1 Computing the Fibonacci Numbers, Version 1 This dynamic-programming algorithm computes the Fibonacci number f [ n ]. It uses the formulas f [1] = 1; f [2] = 1; f [ n ] = f [ n - 1] + f [ n - 2], n ≥ 3. At the conclusion of the algorithm, the array f holds the first n Fibonacci numbers. Input Parameters: n Output Parameters: None fibonacci1 ( n ) { // f is a local array f [1] = 1 f [2] = 1 for i = 3 to n f [ i ] = f [ i - 1] + f [ i - 2] return f [ n ] }
  • 3. Algorithm 8.1.1 Computing the Fibonacci Numbers, Version 2 This dynamic-programming algorithm computes the Fibonacci number f n . It uses the formulas f 1 = 1; f 2 = 1; f n = f n - 1 + f n - 2 , n ≥ 3. It saves the two preceding Fibonacci numbers in the variables f_twoback and f_oneback in order to compute the next Fibonacci number. Input Parameters: n Output Parameters: None fibonacci2 ( n ) { if ( n == 1 || n == 2) return 1 f_twoback = 1 f_oneback = 1 for i = 3 to n { f = f_twoback + f_oneback f_twoback = f_oneback f_oneback = f } return f }
  • 4. Computing the Fibonacci Numbers Recursively This algorithm computes the Fibonacci number f n recursively using the formulas f 1 = 1; f 2 = 1; f n = f n - 1 + f n - 2 , n ≥ 3. Input Parameters: n Output Parameters: None fibonacci_recurs ( n ) { if ( n == 1) return 1 if ( n == 2) return 1 return fibonacci_recurs ( n - 2) + fibonacci_recurs ( n - 1) }
  • 5. Computing the Fibonacci Numbers with Memoization This algorithm computes the Fibonacci number f n recursively (with memoization) using the formulas f 1 = 1; f 2 = 1; f n = f n - 1 + f n - 2 , n ≥ 3.
  • 6. Input Parameters: n Output Parameters: None memoized_fibonacci ( n ) { for i = 1 to n results [ i ] = -1 // -1 means undefined return memoized_fibonacci_recurs ( results , n ) } memoized_fibonacci_recurs ( results , n ) { if ( results [ n ] != -1) return results [ n ] if ( n == 1) val = 1 else if ( n == 2) val = 1 else { val = memoized_fibonacci_recurs ( results , n - 2) val = val + memoized_fibonacci_recurs ( results , n - 1) } results [ n ] = val return val }
  • 7. Algorithm 8.2.1 Coin Changing Using Dynamic Programming, Version 1 This dynamic-programming algorithm computes the minimum number of coins to make change for a given amount. The input is an array denom that specifies the denominations of the coins, denom [1] > denom [2] > ··· > denom [ n ] = 1, and an amount A . The output is an array C whose value, C [ i ][ j ], is the minimum number of coins to make change for the amount j , using coins i through n , 1 ≤ i ≤ n, 0 ≤ j ≤ A.
  • 8. Input Parameters: denoma , A Output Parameters: None dynamic_coin_change1 ( denom , A , C ) { n = denom . last for j = 0 to A C [ n ][ j ] = j for i = n - 1 downto 1 for j = 0 to A if ( denom [ i ] > j || C [ i + 1][ j ] < 1 + C [ i ][ j - denom [ i ]]) C [ i ][ j ] = C [ i + 1][ j ] else C [ i ][ j ] = 1 + C [ i ][ j - denom [ i ]] }
  • 9. Algorithm 8.2.2 Coin Changing Using Dynamic Programming, Version 2 This dynamic-programming algorithm computes the minimum number of coins to make change for a given amount and tracks which coins are used. The input is an array denom that specifies the denominations of the coins, denom [1] > denom [2] > ··· > denom [ n ] = 1, and an amount A . The output consists of arrays C and used . The value, C [ i ][ j ], is the minimum number of coins to make change for the amount j , using coins I through n , 1 ≤ i ≤ n, 0 ≤ j ≤ A. The value, used [ i ][ j ], is true or false to signify whether coin i appears in the smallest set of coins computed by Algorithm 8.2.1 for the amount j using only coins i through n . The values of i and j satisfy 1 ≤ i ≤ n, 0 ≤ j ≤ A.
  • 10. Input Parameters: denom , A Output Parameters: C , used dynamic_coin_change2 ( denom , A , C , used ) { n = denom . last for j = 0 to A { C [ n ][ j ] = j used [ n ][ j ] = true } for i = n - 1 downto 1 for j = 0 to A if ( denom [ i ] > j || C [ i + 1][ j ] < 1 + C [ i ][ j - denom [ i ]]) C [ i ][ j ] = C [ i + 1][ j ] used[ i ][ j ] = false else C [ i ][ j ] = 1 + C [ i ][ j - denom [ i ]] used[ i ][ j ] = true } }
  • 11. Algorithm 8.2.4 Computing a Minimum- Size Set of Coins for a Given Amount This algorithm outputs a minimum-size set of coins to make change for an amount j using any of coins i through n with denominations specified by Algorithm 8.2.2. The algorithm inputs the index i , the amount j , the array denom of Algorithm 8.2.2, and the array used computed by Algorithm 8.2.2.
  • 12. Input Parameters: i , j , denom , used Output Parameters: None optimal_coins_set ( i , j , denom , used ) { if ( j == 0) return if ( used [ i ][ j ]) { println (“Use a coin of denomination ” + denom [ i ]) optimal_coins_set ( i , j - denom [ i ], denom , used ) } else optimal_coins_set ( i + 1, j , denom , used ) }
  • 13. Algorithm 8.3.1 Optimal Matrix Multiplication This algorithm computes the minimum number of scalar multiplications to multiply a sequence of n matrices. The input is the array size that contains the sizes of the matrices to be multiplied. The first matrix is size [0] × size [1]; the second is size [1] × size [2]; and so on. The n th matrix is size [ n - 1] × size [ n ]. The output is the array s whose value, s [ i ][ j ], is the minimum number of scalar multiplications to multiply matrices i through j . The value ∞ is the largest available integer value.
  • 14. Input Parameters: size Output Parameters: s opt_matrix_mult ( size , s ) { n = size . last for i = 1 to n s [ i ][ i ] = 0 // w = j - i for w = 1 to n - 1 for i = 1 to n - w { j = w + i s [ i ][ j ] = ∞ for k = i to j - 1 { q = s [ i ][ k ] + s [ k + 1][ j ] + size [ i - 1] * size [ k ] * size [ j ] if ( q < s [ i ][ j ]) s [ i ][ j ] = q } } }
  • 15. Algorithm 8.4.2 Computing the Length of a Longest Common Subsequence This dynamic-programming algorithm computes the length c [ i ][ j ] of a longest common subsequence of a [1], ... , a[ i ] and b [1], ... , b [ j ] for i = 0, ... , m and j = 0, ... , n . Input Parameters: a , b Output Parameters: c LCS ( a , b , c ) { m = a . last n = b . last for i = 0 to m c [ i ][0] = 0 for j = 1 to n c[0][ j ] = 0 for i = 1 to m for j = 1 to n if ( a [ i ] != b [ j ]) c [ i ][ j ] = max ( c [ i - 1][ j ], c [ i ][ j - 1]) else c [ i ][ j ] = 1 + c [ i - 1][ j - 1] }
  • 16. Algorithm 8.4.3 Computing a Longest Common Subsequence This algorithm uses the array c computed by Algorithm 8.4.2 to output a longest common subsequence. The array a of length m is the first sequence input to Algorithm 8.4.2, and n is the length of the second sequence input to Algorithm 8.4.2. Input Parameters: a , m (length of a ), n (length of second sequence), c (contains lengths of longest common subsequences) Output Parameters: None LCS_print ( a , m , n , c ) { if ( c [ m ][ n ] == 0) return if ( c [ m ][ n ] == c [ m - 1][ n ]) LCS_print ( a , m - 1, n , c ) else if ( c [ m ][ n ] == c [ m ][ n - 1]) LCS_print ( a , m , n - 1, c ) else { LCS_print ( a , m - 1, n - 1, c ) print ( a [ m ]) } }
  • 17. Algorithm 8.5.3 Floyd’s Algorithm, Version 1 This algorithm computes the length of a shortest path between each pair of vertices in a simple, undirected, weighted graph G . All weights are nonnegative. The input is the adjacency matrix A of G . The output is the matrix A whose ij th entry is the length of a shortest path from vertex i to vertex j . Input Parameter: A Output Parameter: A all_paths ( A ) { n = A . last for k = 1 to n // compute A ( k ) for i = 1 to n for j = 1 to n if ( A [ i ][ k ] + A [ k ][ j ] < A [ i ][ j ]) A [ i ][ j ] = A [ i ][ k ] + A [ k ][ j ] }
  • 18. Algorithm 8.5.4 Floyd’s Algorithm, Version 2 This algorithm computes the length of a shortest path between each pair of vertices in a simple, undirected, weighted graph G and stores the vertex that follows the first vertex on each shortest path. All weights are nonnegative. The input is the adjacency matrix A of G . The output is the matrix A whose ij th entry is the length of a shortest path from vertex i to vertex j and the matrix next whose ij th entry is the vertex that follows i on a shortest path from i to j .
  • 19. Input Parameter: A Output Parameter: A , next all_paths ( A , next ) { n = A . last // initialize next: if no intermediate // vertices are allowed next [ i ][ j ] = j for i = 1 to n for j = 1 to n next [ i ][ j ] = j for k = 1 to n // compute A ( k ) for i = 1 to n for j = 1 to n if ( A [ i ][ k ] + A [ k ][ j ] < A [ i ][ j ]) { A [ i ][ j ] = A [ i ][ k ] + A [ k ][ j ] next [ i ][ j ] = next [ i ][ k ] } }
  • 20. Algorithm 8.5.5 Finding a Shortest Path This algorithm outputs a shortest path from vertex i to vertex j in a simple, undirected, weighted graph G . It assumes that matrix next has already been computed by Algorithm 8.5.4. Input Parameters: next , i , j Output Parameters: None print_path ( next , i , j ) { // if no intermediate vertices, just // print i and j and return if ( j == next [ i ][ j ]) { print ( i + “ ” + j ) return } // output i and then the path from the vertex // after i ( next [ i ][ j ]) to j print ( i + “ ”) print_path ( next , next [ i ][ j ], j ) }
  • 21. Algorithm 8.5.12 Warshall’s Algorithm This algorithm computes the transitive closure of a relation R on {1, ... , n }. The input is the matrix A of R . The output is the matrix A of the transitive closure of R . Input Parameters: A Output Parameters: A transitive_closure ( A ) { n = A . last for k = 1 to n for i = 1 to n for j = 1 to n A [ i ][ j ] = A [ i ][ j ]  ( A [ i ][ k ]  A [ k ][ j ]) }