原文:

先决条件: 给定一个矩阵序列,找到将这些矩阵相乘的最有效方法。问题不在于实际执行乘法,而仅仅在于决定以何种顺序执行乘法。 我们有很多选择来相乘矩阵链,因为矩阵乘法是关联的。换句话说,无论我们如何给产品加上括号,结果都是一样的。例如,如果我们有四个矩阵 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[],使得矩阵 ai 的维数为 p[i-1] x p[i]。我们需要编写一个 matrixchainorder()函数,该函数应该返回乘法链所需的最小乘法次数。

input:  p[] = {40, 20, 30, 10, 30} 
output: optimal parenthesization is  ((a(bc))d)
 optimal cost of parenthesization is 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: optimal parenthesization is (((ab)c)d)
 optimal cost of parenthesization is 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: optimal parenthesization is (ab)
 optimal cost of parenthesization is 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

这个问题主要是的延伸。在前一篇文章中,我们只讨论了寻找最优成本的算法。这里我们也需要打印括号。

其思想是将每个子表达式(i,j)的最佳断点存储在 2d 数组括号[n][n]中。一旦我们构造了括号数组,我们就可以使用下面的代码打印括号。

// prints parenthesization in subexpression (i, j)
printparenthesis(i, j, bracket[n][n], name)
{
    // if only one matrix left in current segment
    if (i == j)
    {
        print name;
        name  ;
        return;
    }
    print "(";
    // recursively put brackets around subexpression
    // from i to bracket[i][j].
    printparenthesis(i, bracket[i][j], bracket, name);
    // recursively put brackets around subexpression
    // from bracket[i][j]   1 to j.
    printparenthesis(bracket[i][j] 1, j, bracket, name);
    print ")";
}

下面是上述步骤的实现。

c

// c   program to print optimal parenthesization
// in matrix chain multiplication.
#include 
using namespace std;
// function for printing the optimal
// parenthesization of a matrix chain product
void printparenthesis(int i, int j, int n, int* bracket,
                      char& name)
{
    // if only one matrix left in current segment
    if (i == j) {
        cout << name  ;
        return;
    }
    cout << "(";
    // recursively put brackets around subexpression
    // from i to bracket[i][j].
    // note that "*((bracket i*n) j)" is similar to
    // bracket[i][j]
    printparenthesis(i, *((bracket   i * n)   j), n,
                     bracket, name);
    // recursively put brackets around subexpression
    // from bracket[i][j]   1 to j.
    printparenthesis(*((bracket   i * n)   j)   1, j, n,
                     bracket, name);
    cout << ")";
}
// matrix ai has dimension p[i-1] x p[i] for i = 1..n
// please refer below article for details of this
// function
// https://goo.gl/k6eykj
void matrixchainorder(int p[], int n)
{
    /* for simplicity of the program, one extra
       row and one extra column are allocated in
        m[][]. 0th row and 0th column of m[][]
        are not used */
    int m[n][n];
    // bracket[i][j] stores optimal break point in
    // subexpression from i to j.
    int bracket[n][n];
    /* m[i,j] = minimum number of scalar multiplications
    needed to compute the matrix a[i]a[i 1]...a[j] =
    a[i..j] where dimension of a[i] is p[i-1] x p[i] */
    // cost is zero when multiplying one matrix.
    for (int i = 1; i < n; i  )
        m[i][i] = 0;
    // l is chain length.
    for (int l = 2; l < n; l  )
    {
        for (int i = 1; i < n - l   1; i  )
        {
            int j = i   l - 1;
            m[i][j] = int_max;
            for (int k = i; k <= j - 1; k  )
            {
                // q = cost/scalar multiplications
                int q = m[i][k]   m[k   1][j]
                          p[i - 1] * p[k] * p[j];
                if (q < m[i][j])
                {
                    m[i][j] = q;
                    // each entry bracket[i,j]=k shows
                    // where to split the product arr
                    // i,i 1....j for the minimum cost.
                    bracket[i][j] = k;
                }
            }
        }
    }
    // the first matrix is printed as 'a', next as 'b',
    // and so on
    char name = 'a';
    cout << "optimal parenthesization is : ";
    printparenthesis(1, n - 1, n, (int*)bracket, name);
    cout << "noptimal cost is : " << m[1][n - 1];
}
// driver code
int main()
{
    int arr[] = { 40, 20, 30, 10, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
    matrixchainorder(arr, n);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to print optimal parenthesization
// in matrix chain multiplication.
class gfg
{
  static char name;
  // function for printing the optimal
  // parenthesization of a matrix chain product
  static void printparenthesis(int i, int j,
                               int n, int[][] bracket)
  {
    // if only one matrix left in current segment
    if (i == j)
    {
      system.out.print(name  );
      return;
    }
    system.out.print("(");
    // recursively put brackets around subexpression
    // from i to bracket[i][j].
    // note that "*((bracket i*n) j)" is similar to
    // bracket[i][j]
    printparenthesis(i, bracket[i][j], n, bracket);
    // recursively put brackets around subexpression
    // from bracket[i][j]   1 to j.
    printparenthesis(bracket[i][j]   1, j, n, bracket);
    system.out.print(")");
  }
  // matrix ai has dimension p[i-1] x p[i] for i = 1..n
  // please refer below article for details of this
  // function
  // https://goo.gl/k6eykj
  static void matrixchainorder(int p[], int n)
  {
    /*
         * for simplicity of the program,
         one extra row and one extra column are
         * allocated in m[][]. 0th row and
         0th column of m[][] are not used
         */
    int[][] m = new int[n][n];
    // bracket[i][j] stores optimal break point in
    // subexpression from i to j.
    int[][] bracket = new int[n][n];
    /*
         * m[i,j] = minimum number of scalar
         multiplications needed to compute the
         * matrix a[i]a[i 1]...a[j] = a[i..j] where
         dimension of a[i] is p[i-1] x p[i]
         */
    // cost is zero when multiplying one matrix.
    for (int i = 1; i < n; i  )
      m[i][i] = 0;
    // l is chain length.
    for (int l = 2; l < n; l  )
    {
      for (int i = 1; i < n - l   1; i  )
      {
        int j = i   l - 1;
        m[i][j] = integer.max_value;
        for (int k = i; k <= j - 1; k  )
        {
          // q = cost/scalar multiplications
          int q = m[i][k]   m[k   1][j]   p[i - 1] * p[k] * p[j];
          if (q < m[i][j])
          {
            m[i][j] = q;
            // each entry bracket[i,j]=k shows
            // where to split the product arr
            // i,i 1....j for the minimum cost.
            bracket[i][j] = k;
          }
        }
      }
    }
    // the first matrix is printed as 'a', next as 'b',
    // and so on
    name = 'a';
    system.out.print("optimal parenthesization is : ");
    printparenthesis(1, n - 1, n, bracket);
    system.out.print("\noptimal cost is : "   m[1][n - 1]);
  }
  // driver code
  public static void main(string[] args)
  {
    int arr[] = { 40, 20, 30, 10, 30 };
    int n = arr.length;
    matrixchainorder(arr, n);
  }
}
// this code is contributed by sanjeev2552

c

// c# program to print optimal parenthesization
// in matrix chain multiplication.
using system;
class gfg{
static char name;
// function for printing the optimal
// parenthesization of a matrix chain product
static void printparenthesis(int i, int j,
                             int n, int[,] bracket)
{
    // if only one matrix left in current segment
    if (i == j)
    {
        console.write(name  );
        return;
    }
    console.write("(");
    // recursively put brackets around subexpression
    // from i to bracket[i,j].
    // note that "*((bracket i*n) j)" is similar to
    // bracket[i,j]
    printparenthesis(i, bracket[i, j], n, bracket);
    // recursively put brackets around subexpression
    // from bracket[i,j]   1 to j.
    printparenthesis(bracket[i, j]   1, j, n, bracket);
    console.write(")");
}
// matrix ai has dimension p[i-1] x p[i] for i = 1..n
// please refer below article for details of this
// function
// https://goo.gl/k6eykj
static void matrixchainorder(int []p, int n)
{
    /*
    * for simplicity of the program,
    one extra row and one extra column are
    * allocated in m[,]. 0th row and
    0th column of m[,] are not used
    */
    int[,] m = new int[n, n];
    // bracket[i,j] stores optimal break point in
    // subexpression from i to j.
    int[,] bracket = new int[n, n];
    /*
    * m[i,j] = minimum number of scalar
    multiplications needed to compute the
    * matrix a[i]a[i 1]...a[j] = a[i..j] where
    dimension of a[i] is p[i-1] x p[i]
    */
    // cost is zero when multiplying one matrix.
    for(int i = 1; i < n; i  )
        m[i, i] = 0;
    // l is chain length.
    for(int l = 2; l < n; l  )
    {
        for(int i = 1; i < n - l   1; i  )
        {
            int j = i   l - 1;
            m[i, j] = int.maxvalue;
            for (int k = i; k <= j - 1; k  )
            {
                // q = cost/scalar multiplications
                int q = m[i, k]   m[k   1, j]  
                       p[i - 1] * p[k] * p[j];
                if (q < m[i, j])
                {
                    m[i, j] = q;
                    // each entry bracket[i,j]=k shows
                    // where to split the product arr
                    // i,i 1....j for the minimum cost.
                    bracket[i, j] = k;
                }
            }
        }
    }
    // the first matrix is printed as 'a', next as 'b',
    // and so on
    name = 'a';
    console.write("optimal parenthesization is : ");
    printparenthesis(1, n - 1, n, bracket);
    console.write("\noptimal cost is : "   m[1, n - 1]);
}
// driver code
public static void main(string[] args)
{
    int []arr = { 40, 20, 30, 10, 30 };
    int n = arr.length;
    matrixchainorder(arr, n);
}
}
// this code is contributed by 29ajaykumar

java 描述语言


output

optimal parenthesization is : ((a(bc))d)noptimal cost is : 26000

时间复杂度:o(n3) t5】辅助空间: o(n 2

另一种方法:

——————————————

这个pg电子试玩链接的解决方案试图使用置换递归来解决这个问题。

let's take example:  {40, 20, 30, 10, 30}
n = 5

让我们把它分成一个矩阵

[ [40, 20], [20, 30], [30, 10], [10, 30] ]
[ a , b , c , d ]
it contains 4 matrices i.e. (n - 1)

我们有 3 个组合要相乘,即(n-2)

ab    or    bc    or     cd

算法:

1)给定长度为 m 的矩阵阵列,循环通过 m–1 次

2)合并每个循环中的连续矩阵

for (int i = 0; i < m - 1; i  ) {
   int cost =  (matrices[i][0] * 
                 matrices[i][1] * matrices[i 1][1]);
   // step - 3
   // step - 4
}

3)将当前的两个矩阵合并为一个,并从列表中删除合并的矩阵列表。

if  a, b merged, then a, b must be removed from the list
and new matrix list will be like
newmatrices = [  ab,  c ,  d ]
we have now 3 matrices, in any loop
loop#1:  [ ab,  c,   d ]
loop#2:  [ a,   bc,  d ]
loop#3   [ a,   b,   cd ]

4)重复:以新矩阵作为输入 m-递归进入步骤 1

5)当我们得到列表中的 2 个矩阵时,停止递归。

工作流程

矩阵按以下方式缩减:

在递归过程中,必须保留成本,并将其与每个父步骤的先前值相加。

[ a, b , c, d ]
[(ab), c, d ]
 [ ((ab)c), d ]--> [ (((ab)c)d) ] 
 - return & sum-up total cost of this step.
 [ (ab),  (cd)] --> [ ((ab)(cd)) ] 
 - return .. ditto..
 [ a, (bc), d ]
 [ (a(bc)), d ]--> [ ((a(bc))d) ] 
  - return
 [ a, ((bc)d) ]--> [ (a((bc)d)) ] 
  - return
 [ a, b, (cd) ]
 [ a, (b(cd)) ]--> [ (a(b(cd))) ] 
  - return
 [ (ab), (cd) ]--> [ ((ab)(cd)) ] 
  - return .. ditto..

返回时,即每次递归的最后一步,检查该值是否小于任何其他值。

下面是上述步骤的 java 实现。

java 语言(一种计算机语言,尤用于创建网站)

import java.util.arrays;
public class matrixmultiplycost {
    static class finalcost
    {
        public string label = "";
        public int cost = integer.max_value;
    }
    private void optimalcost(int[][] matrices,
                             string[] labels, int prevcost,
                             finalcost finalcost)
    {
        int len = matrices.length;
        if (len < 2)
        {
            finalcost.cost = 0;
            return;
        }
        else if (len == 2)
        {
            int cost = prevcost
                         (matrices[0][0] *
                          matrices[0][1] *
                          matrices[1][1]);
            // this is where minimal cost has been caught
            // for whole program
            if (cost < finalcost.cost)
            {
                finalcost.cost = cost;
                finalcost.label
                    = "("   labels[0]
                      labels[1]   ")";
            }
            return;
        }
        // recursive reduce
        for (int i = 0; i < len - 1; i  )
        {
            int j;
            int[][] newmatrix = new int[len - 1][2];
            string[] newlabels = new string[len - 1];
            int subindex = 0;
            // step-1:
            //   - merge two matrices's into one - in each
            //   loop, you move merge position
            //        - if i = 0 then  (ab) c d ...
            //        - if i = 1 then  a (bc) d ...
            //        - if i = 2 then  a b (cd) ...
            //   - and find the cost of this two matrices
            //   multiplication
            int cost = (matrices[i][0] * matrices[i][1]
                        * matrices[i   1][1]);
            // step - 2:
            //    - build new matrices after merge
            //    - keep track of the merged labels too
            for (j = 0; j < i; j  ) {
                newmatrix[subindex] = matrices[j];
                newlabels[subindex  ] = labels[j];
            }
            newmatrix[subindex][0] = matrices[i][0];
            newmatrix[subindex][1] = matrices[i   1][1];
            newlabels[subindex  ]
                = "("   labels[i]   labels[i   1]   ")";
            for (j = i   2; j < len; j  ) {
                newmatrix[subindex] = matrices[j];
                newlabels[subindex  ] = labels[j];
            }
            optimalcost(newmatrix, newlabels,
                        prevcost   cost, finalcost);
        }
    }
    public finalcost findoptionalcost(int[] arr)
    {
        // step -1 : prepare and convert inout as matrix
        int[][] matrices = new int[arr.length - 1][2];
        string[] labels = new string[arr.length - 1];
        for (int i = 0; i < arr.length - 1; i  ) {
            matrices[i][0] = arr[i];
            matrices[i][1] = arr[i   1];
            labels[i] = character.tostring((char)(65   i));
        }
        printmatrix(matrices);
        finalcost finalcost = new finalcost();
        optimalcost(matrices, labels, 0, finalcost);
        return finalcost;
    }
    /**
     * driver code
     */
    public static void main(string[] args)
    {
        matrixmultiplycost calc = new matrixmultiplycost();
        // ======= *** test cases **** ============
        int[] arr = { 40, 20, 30, 10, 30 };
        finalcost cost = calc.findoptionalcost(arr);
        system.out.println("final labels: \n"   cost.label);
        system.out.println("final cost:\n"   cost.cost
                             "\n");
    }
    /**
     * ignore this method
     * - this is for display purpose only
     */
    private static void printmatrix(int[][] matrices)
    {
        system.out.print("matrices = \n[");
        for (int[] row : matrices) {
            system.out.print(arrays.tostring(row)   " ");
        }
        system.out.println("]");
    }
}
// this code is contributed by suvera

output

matrices = 
[[40, 20] [20, 30] [30, 10] [10, 30] ]
final labels: 
((a(bc))d)
final cost:
26000

本文由亚辛·扎法尔供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。