原文:

先决条件: 给定一个矩阵序列,找到将这些矩阵相乘的最有效方法。问题不在于实际执行乘法,而仅仅在于决定以何种顺序执行乘法。

我们有很多选择来乘矩阵链,因为矩阵乘法是关联的。换句话说,无论我们如何给产品加上括号,结果都是一样的。例如,如果我们有四个矩阵 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 the parenthesis in the 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 the parenthesis in the 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, the cost of which is 10*20*30

这个问题主要是最优成本的一个延伸。这里我们还需要打印括号。

我们在一篇帖子中讨论了一个使用两个矩阵的pg电子试玩链接的解决方案。在这篇文章中,讨论了一个使用单一矩阵的空间优化pg电子试玩链接的解决方案。 1)为了找到最优成本,我们创建了一个矩阵,该矩阵只有上三角被填充,其余的单元没有被使用。 2)思路是用同一个矩阵的下三角部分(不使用的部分)存放括号。 想法是在 m [ j ][ i ]存储每个子表达式(i,j)的最优断点,在 m [ i ] [ j ]存储最优成本。

下面是以上步骤的实现。

c

// a space optimized 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[j][i].
    // note that "*((bracket j*n) i)" is similar to
    // bracket[j][i]
    printparenthesis(i, *((bracket j*n) i), n,
                     bracket, name);
    // recursively put brackets around subexpression
    // from bracket[j][i]   1 to i.
    printparenthesis(*((bracket j*n) i)   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];
    /* 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

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

// a space optimized java program to print optimal
// parenthesization in matrix chain multiplication.
import java.util.*;
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[j][i].
        // note that "*((bracket j*n) i)" is similar to
        // bracket[i][j]
        printparenthesis(i, bracket[j][i], n, bracket);
        // recursively put brackets around subexpression
        // from bracket[j][i]   1 to i.
        printparenthesis(bracket[j][i]   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];
        /*
        * 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 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 m[j,ji=k shows
                        // where to split the product arr
                        // i,i 1....j for the minimum cost.
                        m[j][i] = 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, m);
        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

python 3

# a space optimized python3 program to
# print optimal parenthesization in
# matrix chain multiplication.
def printparenthesis(m, j, i ):
    # displaying the parenthesis.
    if j == i:
        # the first matrix is printed as
        # 'a', next as 'b', and so on
        print(chr(65   j), end = "")
        return;
    else:
        print("(", end = "")
        # passing (m, k, i) instead of (s, i, k)
        printparenthesis(m, m[j][i] - 1, i)
        # (m, j, k 1) instead of (s, k 1, j)
        printparenthesis(m, j, m[j][i])
        print (")", end = "" )
def matrixchainorder(p, n):
    # creating a matrix of order
    # n*n in the memory.
    m = [[0 for i in range(n)]
            for i in range (n)]
    for l in range (2, n   1):
        for i in range (n - l   1):
            j = i   l - 1
            # initializing infinity value.
            m[i][j] = float('inf')
            for k in range (i, j):
                q = (m[i][k]   m[k   1][j]  
                    (p[i] * p[k   1] * p[j   1]));
                if (q < m[i][j]):
                    m[i][j] = q
                    # storing k value in opposite index.
                    m[j][i] = k   1
    return m;
# driver code
arr = [40, 20, 30, 10, 30]
n = len(arr) - 1
m = matrixchainorder(arr, n) # forming the matrix m
print("optimal parenthesization is: ", end = "")
# passing the index of the bottom left
# corner of the 'm' matrix instead of
# passing the index of the top right
# corner of the 's' matrix as we used
# to do earlier. everything is just opposite
# as we are using the bottom half of the
# matrix so assume everything opposite even
# the index, take m[j][i].
printparenthesis(m, n - 1, 0)
print("\noptimal cost is :", m[0][n - 1])
# this code is contributed by akash gupta.

c

// a space optimized 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[j,i].
    // note that "*((bracket j*n) i)" is similar to
    // bracket[i,j]
    printparenthesis(i, bracket[j, i], n, bracket);
    // recursively put brackets around subexpression
    // from bracket[j,i]   1 to i.
    printparenthesis(bracket[j, i]   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];
    /*
    * 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 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 m[j,ji=k shows
                    // where to split the product arr
                    // i,i 1....j for the minimum cost.
                    m[j, i] = 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, m);
    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 princi singh

output: 

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

时间复杂度:o(n^3) t3】辅助空间: o(n^2):这个渐近值保持不变,但是我们把辅助空间减少到一半。