📜  矩阵链乘法的Python程序 | DP-8

📅  最后修改于: 2022-05-13 01:56:56.782000             🧑  作者: Mango

矩阵链乘法的Python程序 | DP-8

给定一个矩阵序列,找到将这些矩阵相乘的最有效方法。问题实际上不是执行乘法,而只是决定执行乘法的顺序。

我们有很多选择来乘以矩阵链,因为矩阵乘法是关联的。换句话说,无论我们如何给产品加上括号,结果都是一样的。例如,如果我们有四个矩阵 A、B、C 和 D,我们将有:

(ABC)D = (AB)(CD) = A(BCD) = ....

但是,我们将乘积括起来的顺序会影响计算乘积所需的简单算术运算的数量或效率。例如,假设 A 是 10 × 30 矩阵,B 是 30 × 5 矩阵,C 是 5 × 60 矩阵。然后,

(AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations
    A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.

显然,第一个括号需要较少的操作。

给定一个数组 p[],它表示矩阵链,使得第 i 个矩阵 Ai 的维数为 p[i-1] xp[i]。我们需要编写一个函数MatrixChainOrder(),它应该返回乘以链所需的最小乘法次数。

Input: p[] = {40, 20, 30, 10, 30}   
  Output: 26000  
  There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of 
  multiplications are obtained by putting parenthesis in following way
  (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

  Input: p[] = {10, 20, 30, 40, 30} 
  Output: 30000 
  There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30. 
  Let the input 4 matrices be A, B, C and D.  The minimum number of 
  multiplications are obtained by putting parenthesis in following way
  ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

  Input: p[] = {10, 20, 30}  
  Output: 6000  
  There are only two matrices of dimensions 10x20 and 20x30. So there 
  is only one way to multiply the matrices, cost of which is 10*20*30