📜  C矩阵链乘法程序|德州仪器TI.com.cn DP-8

📅  最后修改于: 2021-05-28 03:19:36             🧑  作者: Mango

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

因为矩阵乘法是关联的,所以我们有很多选择可以乘法矩阵链。换句话说,无论我们如何对产品加上括号,结果都是一样的。例如,如果我们有四个矩阵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