SlideShare una empresa de Scribd logo
1 de 25
Dynamic Programming


                Lecture 16
Dynamic Programming
 Dynamic programming is typically applied to optimization
  problems. In such problems there can be many possible
  solutions. Each solution has a value, and we wish to find a
  solution with the optimal (minimum or maximum) value.
Dynamic Programming
 Like divide and conquer, Dynamic Programming solves
  problems by combining solutions to sub problems.
 Unlike divide and conquer, sub problems are not
  independent.
    Subproblems may share subsubproblems,
    However, solution to one subproblem may not affect the solutions
     to other subproblems of the same problem. (More on this later.)
 Dynamic Programming reduces computation by
    Solving subproblems in a bottom-up fashion.
    Storing solution to a subproblem the first time it is solved.
    Looking up the solution when subproblem is encountered again
Dynamic Programming
The development of a dynamic-programming algorithm can be
broken into a sequence of four steps.
1.Characterize the structure of an optimal solution.
2.Recursively define the value of an optimal solution.
3.Compute the value of an optimal solution in a bottom-up
fashion.
4.Construct an optimal solution from computed information.
Matrix-chain Multiplication
   Suppose we have a sequence or chain A1, A2, …, An of n
    matrices to be multiplied
       That is, we want to compute the product A1A2…An

   There are many possible ways (parenthesizations) to compute
    the product
Matrix-chain Multiplication
    Example: consider the chain A1, A2, A3, A4 of 4 matrices
        Let us compute the product A1A2A3A4
    There are 5 possible ways:
    1.   (A1(A2(A3A4)))
    2.   (A1((A2A3)A4))
    3.   ((A1A2)(A3A4))
    4.   ((A1(A2A3))A4)
    5.   (((A1A2)A3)A4)
Algorithm to Multiply 2 Matrices

Input: Matrices Ap×q and Bq×r (with dimensions p×q and q×r)
Result: Matrix Cp×r resulting from the product A·B

MATRIX-MULTIPLY(Ap×q , Bq×r)
1. for i ← 1 to p
2.           for j ← 1 to r
3.                  C[i, j] ← 0
4.                  for k ← 1 to q
5.                          C[i, j] ← C[i, j] + A[i, k] · B[k, j]
6. return C
Matrix-chain Multiplication
   Example: Consider three matrices A10×100, B100×5, and C5×50
   There are 2 ways to parenthesize
       ((AB)C) = D10×5 · C5×50
         AB ⇒ 10·100·5=5,000 scalar multiplications
         DC ⇒ 10·5·50 =2,500 scalar multiplications
       (A(BC)) = A10×100 · E100×50
         BC ⇒ 100·5·50=25,000 scalar multiplications
         AE ⇒ 10·100·50 =50,000 scalar multiplications
Matrix-chain Multiplication Problem
   Matrix-chain multiplication problem
       Given a chain A1, A2, …, An of n matrices, where for i=1, 2, …, n,
        matrix Ai has dimension pi-1×pi
       Parenthesize the product A1A2…An such that the total number of
        scalar multiplications is minimized
   Brute force method of exhaustive search takes time exponential in
    n
Step 1: The structure of an optimal
parenthesization
 The optimal substructure of this problem is as follows.
 Suppose that the optimal parenthesization of AiAi+1…Aj splits
  the product between Ak and Ak+1. Then the parenthesization
  of the subchain AiAi+1…Ak within this optimal
  parenthesization of AiAi+1…Aj must be an optimal
  parenthesization of AiAi+1…Ak.
 A similar observation holds for the parenthesization of the
  subchain Ak+1Ak+2…Aj in the optimal parenthesization of
  AiAi+1…Aj.
Step 2: A recursive solution
 Let m[i, j] be the minimum number of scalar
  multiplications needed to compute the matrix
  AiAi+1…Aj; the cost of a cheapest way to compute
  A1A2…An would thus be m[1, n].
            0
                                                          i= j
 m[i, j ] = 
              min{m[i, k ] + m[k + 1, j ] + pi −1 pk p j } i < j
             i ≤k < j
            
Step 3: Computing the optimal costs
MATRIX-CHAIN-ORDER(p)
1 n←length[p] - 1
2 for i←1 to n
3    do m[i, i]←0
4    for l←2 to n
5      do for i←1 to n - l + 1
6          do j ←i + l-1
7              m[i, j]←∞
8              for k←i to j - 1
9                 do q←m[i, k] + m[k + 1, j] +pi-1pkpj
10          if q < m[i, j]
11            then m[i, j]←q
12                    s[i, j]←k
13 return m and s
 It’s running time is O(n3).
matrix dimension
----------------------
  A1 30 X 35
  A2 35 X 15
  A3       15 X 5
  A4       5 X 10
  A5 10 X 20
  A6 20 X 25
Step 4: Constructing an optimal solution
PRINT-OPTIMAL-PARENS(s, i, ,j)
1 if j =i
2 then print “A”,i
3 else print “(”
4         PRINT-OPTIMAL-PARENS(s, i, s[i, j])
5         PRINT-OPTIMAL-PARENS(s, s[i, j] + 1, j)
6         print “)”

    In the above example, the call PRINT-OPTIMAL-
     PARENS(s, 1, 6) computes the matrix-chain product
     according to the parenthesization
                     ((A1(A2A3))((A4A5)A6)) .
Longest common subsequence
 Formally, given a sequence X ={x1, x2, . . . , xm}, another sequence
  Z ={z1, z2, . . . , zk} is a subsequence of X if there exists a strictly
  increasing sequence i1, i2, . . . , ik of indices of X such that for all j
  = 1, 2, . . . , k, we have xij = zj. For example, Z ={B, C, D, B} is a
  subsequence of X ={A, B, C, B, D, A, B } with corresponding
  index sequence {2, 3, 5, 7}.
 Given two sequences X and Y, we say that a sequence Z is a
  common subsequence of X and Y if Z is a subsequence of both X
  and Y.
 In the longest-common-subsequence problem, we are given two
  sequences X = {x1, x2, . . . , xm} and Y ={y1, y2, . . . , yn} and wish to
  find a maximum-length common subsequence of X and Y.
Step 1: Characterizing a longest common
subsequence
 Let X ={x1, x2, . . . , xm} and Y ={y1, y2, . . . , yn} be
  sequences, and let Z ={z1, z2, . . . , zk} be any LCS of
  X and Y.
 1. If xm = yn, then zk = xm = yn and Zk-l is an LCS of Xm-l
  and Yn-l.
 2. If xm≠yn, then zk≠xm implies that Z is an LCS of Xm-1
  and Y.
 3. If xm≠yn, then zk≠yn implies that Z is an LCS of X
  and Yn-l.
Step 2: A recursive solution to
 subproblems
 Let us define c[i, j] to be the length of an LCS of the sequences Xi
  and Yj. The optimal substructure of the LCS problem gives the
  recursive formula




                  0                              i = 0orj = 0
                  
       c[i, j ] = c[i − 1, j − 1] + 1            i, j > 0andxi = y j
                  max(c[i, j − 1], c[i − 1, j ]) i, j > 0andx ≠ y
                                                              i    j
Step 3: Computing the length of an LCS

LCS-LENGTH(X,Y)
1 m←length[X]
2 n←length[Y]
3 for i←1 to m
4 do c[i,0]←0
5 for j←0 to n
6 do c[0, j]←0
7 for i←1 to m
8 do for j←1 to n
9       do if xi = yj
10           then c[i, j]←c[i - 1, j -1] + 1
11                    b[i, j] ←”↖”
12           else if c[i - 1, j]←c[i, j - 1]
13                     then c[i, j]←c[i - 1, j]
14                            b[i, j] ←”↑”
15                     else c[i, j]←c[i, j -1]
16                            b[i, j] ←”←”
17 return c and b
The running time of the procedure is
O(mn).



x=ABCBDAB and y=BDCABA,
Step 4: Constructing an LCS
PRINT-LCS(b,X,i,j)
1 if i = 0 or j = 0
2 then return
3 if b[i, j] = “↖"
4 then PRINT-LCS(b,X,i - 1, j - 1)
5           print xi
6 elseif b[i,j] = “↑"
7            then PRINT-LCS(b,X,i - 1,j)
8          else PRINT-LCS(b,X,i, j - 1)
Elements of dynamic programming
 For dynamic programming, Optimization problem must
  have following to be applicable
 optimal substructure
 overlapping subproblems
 Memoization.
Optimal substructure
 The first step in solving an optimization problem by
  dynamic programming is to characterize the structure of an
  optimal solution. We say that a problem exhibits optimal
  substructure if an optimal solution to the problem contains
  within it optimal solutions to subproblems. Whenever a
  problem exhibits optimal substructure, it is a good clue that
  dynamic programming might apply.
Overlapping subproblems
 When a recursive algorithm revisits the same problem over
  and over again, we say that the optimization problem has
  overlapping subproblems
Memoization
 A memoized recursive algorithm maintains an entry in a
  table for the solution to each subproblem.
 Each table entry initially contains a special value to indicate
  that the entry has yet to be filled in.
 When the subproblem is first encountered during the
  execution of the recursive algorithm, its solution is
  computed and then stored in the table.
 Each subsequent time that the subproblem is encountered,
  the value stored in the table is simply looked up and
  returned.

Más contenido relacionado

La actualidad más candente

A series of maximum entropy upper bounds of the differential entropy
A series of maximum entropy upper bounds of the differential entropyA series of maximum entropy upper bounds of the differential entropy
A series of maximum entropy upper bounds of the differential entropyFrank Nielsen
 
Classification with mixtures of curved Mahalanobis metrics
Classification with mixtures of curved Mahalanobis metricsClassification with mixtures of curved Mahalanobis metrics
Classification with mixtures of curved Mahalanobis metricsFrank Nielsen
 
Assessments for class xi
Assessments  for class  xi Assessments  for class  xi
Assessments for class xi indu psthakur
 
Andrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshopAndrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshopAndries Rusu
 
Bregman divergences from comparative convexity
Bregman divergences from comparative convexityBregman divergences from comparative convexity
Bregman divergences from comparative convexityFrank Nielsen
 
The dual geometry of Shannon information
The dual geometry of Shannon informationThe dual geometry of Shannon information
The dual geometry of Shannon informationFrank Nielsen
 
IRJET- On Greatest Common Divisor and its Application for a Geometrical S...
IRJET-  	  On Greatest Common Divisor and its Application for a Geometrical S...IRJET-  	  On Greatest Common Divisor and its Application for a Geometrical S...
IRJET- On Greatest Common Divisor and its Application for a Geometrical S...IRJET Journal
 
Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Alexander Litvinenko
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsemGopi Saiteja
 
Convex optimization methods
Convex optimization methodsConvex optimization methods
Convex optimization methodsDong Guo
 
class 12 2014 maths solution set 1
class 12 2014 maths solution set 1class 12 2014 maths solution set 1
class 12 2014 maths solution set 1vandna123
 
Indefinite and Definite Integrals Using the Substitution Method
Indefinite and Definite Integrals Using the Substitution MethodIndefinite and Definite Integrals Using the Substitution Method
Indefinite and Definite Integrals Using the Substitution MethodScott Bailey
 
1609 probability function p on subspace of s
1609 probability function p on subspace of s1609 probability function p on subspace of s
1609 probability function p on subspace of sDr Fereidoun Dejahang
 
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMS
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMSSOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMS
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMSTahia ZERIZER
 
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT KanpurMid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT KanpurVivekananda Samiti
 
Maths chapter wise Important questions
Maths chapter wise Important questionsMaths chapter wise Important questions
Maths chapter wise Important questionsSrikanth KS
 

La actualidad más candente (20)

A series of maximum entropy upper bounds of the differential entropy
A series of maximum entropy upper bounds of the differential entropyA series of maximum entropy upper bounds of the differential entropy
A series of maximum entropy upper bounds of the differential entropy
 
Classification with mixtures of curved Mahalanobis metrics
Classification with mixtures of curved Mahalanobis metricsClassification with mixtures of curved Mahalanobis metrics
Classification with mixtures of curved Mahalanobis metrics
 
Assessments for class xi
Assessments  for class  xi Assessments  for class  xi
Assessments for class xi
 
Andrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshopAndrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshop
 
Bregman divergences from comparative convexity
Bregman divergences from comparative convexityBregman divergences from comparative convexity
Bregman divergences from comparative convexity
 
The dual geometry of Shannon information
The dual geometry of Shannon informationThe dual geometry of Shannon information
The dual geometry of Shannon information
 
Assignmen ts --x
Assignmen ts  --xAssignmen ts  --x
Assignmen ts --x
 
IRJET- On Greatest Common Divisor and its Application for a Geometrical S...
IRJET-  	  On Greatest Common Divisor and its Application for a Geometrical S...IRJET-  	  On Greatest Common Divisor and its Application for a Geometrical S...
IRJET- On Greatest Common Divisor and its Application for a Geometrical S...
 
Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsem
 
Convex optimization methods
Convex optimization methodsConvex optimization methods
Convex optimization methods
 
class 12 2014 maths solution set 1
class 12 2014 maths solution set 1class 12 2014 maths solution set 1
class 12 2014 maths solution set 1
 
Dynamic programming lcs
Dynamic programming lcsDynamic programming lcs
Dynamic programming lcs
 
Finite fields
Finite fields Finite fields
Finite fields
 
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
Program on Quasi-Monte Carlo and High-Dimensional Sampling Methods for Applie...
 
Indefinite and Definite Integrals Using the Substitution Method
Indefinite and Definite Integrals Using the Substitution MethodIndefinite and Definite Integrals Using the Substitution Method
Indefinite and Definite Integrals Using the Substitution Method
 
1609 probability function p on subspace of s
1609 probability function p on subspace of s1609 probability function p on subspace of s
1609 probability function p on subspace of s
 
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMS
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMSSOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMS
SOLVING BVPs OF SINGULARLY PERTURBED DISCRETE SYSTEMS
 
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT KanpurMid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
Mid semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
 
Maths chapter wise Important questions
Maths chapter wise Important questionsMaths chapter wise Important questions
Maths chapter wise Important questions
 

Similar a Dynamic1

5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03Krish_ver2
 
Chapter 5.pptx
Chapter 5.pptxChapter 5.pptx
Chapter 5.pptxTekle12
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmRajKumar323561
 
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog217-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2Shanmuganathan C
 
Free video lectures for mca
Free video lectures for mcaFree video lectures for mca
Free video lectures for mcaEdhole.com
 
AAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxAAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxHarshitSingh334328
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programminghodcsencet
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programingrupali_2bonde
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfjannatulferdousmaish
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1debolina13
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingGopi Saiteja
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesignRespa Peter
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals reviewElifTech
 
DynamicProgramming.ppt
DynamicProgramming.pptDynamicProgramming.ppt
DynamicProgramming.pptDavidMaina47
 
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhhCh3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhhdanielgetachew0922
 
9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.pptKerbauBakar
 
Applied Algorithms and Structures week999
Applied Algorithms and Structures week999Applied Algorithms and Structures week999
Applied Algorithms and Structures week999fashiontrendzz20
 

Similar a Dynamic1 (20)

5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03
 
Chapter 5.pptx
Chapter 5.pptxChapter 5.pptx
Chapter 5.pptx
 
Matrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithmMatrix chain multiplication in design analysis of algorithm
Matrix chain multiplication in design analysis of algorithm
 
17-dynprog2.ppt
17-dynprog2.ppt17-dynprog2.ppt
17-dynprog2.ppt
 
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog217-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
17-dynprog2 17-dynprog2 17-dynprog2 17-dynprog2
 
Free video lectures for mca
Free video lectures for mcaFree video lectures for mca
Free video lectures for mca
 
Daa chapter 3
Daa chapter 3Daa chapter 3
Daa chapter 3
 
AAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxAAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptx
 
unit-4-dynamic programming
unit-4-dynamic programmingunit-4-dynamic programming
unit-4-dynamic programming
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Signals and Systems Homework Help.pptx
Signals and Systems Homework Help.pptxSignals and Systems Homework Help.pptx
Signals and Systems Homework Help.pptx
 
Matrix multiplicationdesign
Matrix multiplicationdesignMatrix multiplicationdesign
Matrix multiplicationdesign
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
DynamicProgramming.ppt
DynamicProgramming.pptDynamicProgramming.ppt
DynamicProgramming.ppt
 
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhhCh3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
Ch3(1).pptxbbbbbbbbbbbbbbbbbbbhhhhhhhhhh
 
9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt
 
Applied Algorithms and Structures week999
Applied Algorithms and Structures week999Applied Algorithms and Structures week999
Applied Algorithms and Structures week999
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Último (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

Dynamic1

  • 1. Dynamic Programming Lecture 16
  • 2. Dynamic Programming  Dynamic programming is typically applied to optimization problems. In such problems there can be many possible solutions. Each solution has a value, and we wish to find a solution with the optimal (minimum or maximum) value.
  • 3. Dynamic Programming  Like divide and conquer, Dynamic Programming solves problems by combining solutions to sub problems.  Unlike divide and conquer, sub problems are not independent.  Subproblems may share subsubproblems,  However, solution to one subproblem may not affect the solutions to other subproblems of the same problem. (More on this later.)  Dynamic Programming reduces computation by  Solving subproblems in a bottom-up fashion.  Storing solution to a subproblem the first time it is solved.  Looking up the solution when subproblem is encountered again
  • 4. Dynamic Programming The development of a dynamic-programming algorithm can be broken into a sequence of four steps. 1.Characterize the structure of an optimal solution. 2.Recursively define the value of an optimal solution. 3.Compute the value of an optimal solution in a bottom-up fashion. 4.Construct an optimal solution from computed information.
  • 5. Matrix-chain Multiplication  Suppose we have a sequence or chain A1, A2, …, An of n matrices to be multiplied  That is, we want to compute the product A1A2…An  There are many possible ways (parenthesizations) to compute the product
  • 6. Matrix-chain Multiplication  Example: consider the chain A1, A2, A3, A4 of 4 matrices  Let us compute the product A1A2A3A4  There are 5 possible ways: 1. (A1(A2(A3A4))) 2. (A1((A2A3)A4)) 3. ((A1A2)(A3A4)) 4. ((A1(A2A3))A4) 5. (((A1A2)A3)A4)
  • 7. Algorithm to Multiply 2 Matrices Input: Matrices Ap×q and Bq×r (with dimensions p×q and q×r) Result: Matrix Cp×r resulting from the product A·B MATRIX-MULTIPLY(Ap×q , Bq×r) 1. for i ← 1 to p 2. for j ← 1 to r 3. C[i, j] ← 0 4. for k ← 1 to q 5. C[i, j] ← C[i, j] + A[i, k] · B[k, j] 6. return C
  • 8. Matrix-chain Multiplication  Example: Consider three matrices A10×100, B100×5, and C5×50  There are 2 ways to parenthesize  ((AB)C) = D10×5 · C5×50  AB ⇒ 10·100·5=5,000 scalar multiplications  DC ⇒ 10·5·50 =2,500 scalar multiplications  (A(BC)) = A10×100 · E100×50  BC ⇒ 100·5·50=25,000 scalar multiplications  AE ⇒ 10·100·50 =50,000 scalar multiplications
  • 9. Matrix-chain Multiplication Problem  Matrix-chain multiplication problem  Given a chain A1, A2, …, An of n matrices, where for i=1, 2, …, n, matrix Ai has dimension pi-1×pi  Parenthesize the product A1A2…An such that the total number of scalar multiplications is minimized  Brute force method of exhaustive search takes time exponential in n
  • 10. Step 1: The structure of an optimal parenthesization  The optimal substructure of this problem is as follows.  Suppose that the optimal parenthesization of AiAi+1…Aj splits the product between Ak and Ak+1. Then the parenthesization of the subchain AiAi+1…Ak within this optimal parenthesization of AiAi+1…Aj must be an optimal parenthesization of AiAi+1…Ak.  A similar observation holds for the parenthesization of the subchain Ak+1Ak+2…Aj in the optimal parenthesization of AiAi+1…Aj.
  • 11. Step 2: A recursive solution  Let m[i, j] be the minimum number of scalar multiplications needed to compute the matrix AiAi+1…Aj; the cost of a cheapest way to compute A1A2…An would thus be m[1, n]. 0  i= j m[i, j ] =  min{m[i, k ] + m[k + 1, j ] + pi −1 pk p j } i < j  i ≤k < j 
  • 12. Step 3: Computing the optimal costs MATRIX-CHAIN-ORDER(p) 1 n←length[p] - 1 2 for i←1 to n 3 do m[i, i]←0 4 for l←2 to n 5 do for i←1 to n - l + 1 6 do j ←i + l-1 7 m[i, j]←∞ 8 for k←i to j - 1 9 do q←m[i, k] + m[k + 1, j] +pi-1pkpj 10 if q < m[i, j] 11 then m[i, j]←q 12 s[i, j]←k 13 return m and s  It’s running time is O(n3).
  • 13. matrix dimension ---------------------- A1 30 X 35 A2 35 X 15 A3 15 X 5 A4 5 X 10 A5 10 X 20 A6 20 X 25
  • 14. Step 4: Constructing an optimal solution PRINT-OPTIMAL-PARENS(s, i, ,j) 1 if j =i 2 then print “A”,i 3 else print “(” 4 PRINT-OPTIMAL-PARENS(s, i, s[i, j]) 5 PRINT-OPTIMAL-PARENS(s, s[i, j] + 1, j) 6 print “)”  In the above example, the call PRINT-OPTIMAL- PARENS(s, 1, 6) computes the matrix-chain product according to the parenthesization ((A1(A2A3))((A4A5)A6)) .
  • 15. Longest common subsequence  Formally, given a sequence X ={x1, x2, . . . , xm}, another sequence Z ={z1, z2, . . . , zk} is a subsequence of X if there exists a strictly increasing sequence i1, i2, . . . , ik of indices of X such that for all j = 1, 2, . . . , k, we have xij = zj. For example, Z ={B, C, D, B} is a subsequence of X ={A, B, C, B, D, A, B } with corresponding index sequence {2, 3, 5, 7}.
  • 16.  Given two sequences X and Y, we say that a sequence Z is a common subsequence of X and Y if Z is a subsequence of both X and Y.  In the longest-common-subsequence problem, we are given two sequences X = {x1, x2, . . . , xm} and Y ={y1, y2, . . . , yn} and wish to find a maximum-length common subsequence of X and Y.
  • 17. Step 1: Characterizing a longest common subsequence  Let X ={x1, x2, . . . , xm} and Y ={y1, y2, . . . , yn} be sequences, and let Z ={z1, z2, . . . , zk} be any LCS of X and Y. 1. If xm = yn, then zk = xm = yn and Zk-l is an LCS of Xm-l and Yn-l. 2. If xm≠yn, then zk≠xm implies that Z is an LCS of Xm-1 and Y. 3. If xm≠yn, then zk≠yn implies that Z is an LCS of X and Yn-l.
  • 18. Step 2: A recursive solution to subproblems  Let us define c[i, j] to be the length of an LCS of the sequences Xi and Yj. The optimal substructure of the LCS problem gives the recursive formula 0 i = 0orj = 0  c[i, j ] = c[i − 1, j − 1] + 1 i, j > 0andxi = y j max(c[i, j − 1], c[i − 1, j ]) i, j > 0andx ≠ y  i j
  • 19. Step 3: Computing the length of an LCS LCS-LENGTH(X,Y) 1 m←length[X] 2 n←length[Y] 3 for i←1 to m 4 do c[i,0]←0 5 for j←0 to n 6 do c[0, j]←0 7 for i←1 to m 8 do for j←1 to n 9 do if xi = yj 10 then c[i, j]←c[i - 1, j -1] + 1 11 b[i, j] ←”↖” 12 else if c[i - 1, j]←c[i, j - 1] 13 then c[i, j]←c[i - 1, j] 14 b[i, j] ←”↑” 15 else c[i, j]←c[i, j -1] 16 b[i, j] ←”←” 17 return c and b
  • 20. The running time of the procedure is O(mn). x=ABCBDAB and y=BDCABA,
  • 21. Step 4: Constructing an LCS PRINT-LCS(b,X,i,j) 1 if i = 0 or j = 0 2 then return 3 if b[i, j] = “↖" 4 then PRINT-LCS(b,X,i - 1, j - 1) 5 print xi 6 elseif b[i,j] = “↑" 7 then PRINT-LCS(b,X,i - 1,j) 8 else PRINT-LCS(b,X,i, j - 1)
  • 22. Elements of dynamic programming  For dynamic programming, Optimization problem must have following to be applicable  optimal substructure  overlapping subproblems  Memoization.
  • 23. Optimal substructure  The first step in solving an optimization problem by dynamic programming is to characterize the structure of an optimal solution. We say that a problem exhibits optimal substructure if an optimal solution to the problem contains within it optimal solutions to subproblems. Whenever a problem exhibits optimal substructure, it is a good clue that dynamic programming might apply.
  • 24. Overlapping subproblems  When a recursive algorithm revisits the same problem over and over again, we say that the optimization problem has overlapping subproblems
  • 25. Memoization  A memoized recursive algorithm maintains an entry in a table for the solution to each subproblem.  Each table entry initially contains a special value to indicate that the entry has yet to be filled in.  When the subproblem is first encountered during the execution of the recursive algorithm, its solution is computed and then stored in the table.  Each subsequent time that the subproblem is encountered, the value stored in the table is simply looked up and returned.