The Wayback Machine - https://web.archive.org/web/20240817142738/https://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/
Open In App

Printing brackets in Matrix Chain Multiplication Problem

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.

We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have: 

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

However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,  

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

Clearly the first parenthesization requires less number of operations.

Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain. 

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

This problem is mainly an extension of previous post. In the previous post, we have discussed algorithm for finding optimal cost only. Here we need print parenthesization also.

The idea is to store optimal break point for every subexpression (i, j) in a 2D array bracket[n][n]. Once we have bracket array us constructed, we can print parenthesization using below code. 

// 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 ")";
}

Below is the implementation of the above steps.

C++




// C++ program to print optimal parenthesization
// in matrix chain multiplication.
#include <bits/stdc++.h>
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
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.
import java.io.*;
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[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
    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


Python3




# Python3 program to print optimal parenthesization
# in matrix chain multiplication.
name = 0;
 
# Function for printing the optimal
# parenthesization of a matrix chain product
def printParenthesis(i , j, n, bracket):
     
    global name
   
    # If only one matrix left in current segment
    if (i == j):
     
        print(name, end = "");
        name = chr(ord(name) + 1)
        return;
     
    print("(", end = "");
 
    # 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);
    print(")", end = "");
   
# 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
def matrixChainOrder( p , n):
     
    global name
   
    '''
         * 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
         '''
    m = [ [0 for _ in range(n)] for _ in range(n)]
 
    # bracket[i][j] stores optimal break point in
    # subexpression from i to j.
    bracket = [ [0 for _ in range(n)] for _ in range(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  i in range(1, n):
        m[i][i] = 0;
 
    # L is chain length.
    for L in range(2, n):
         
        for i in range(1, n - L + 1):
            j = i + L - 1;
            m[i][j] = 10 ** 8;
            for k in range(i, j):
 
                # q = cost/scalar multiplications
                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';
    print("Optimal Parenthesization is : ");
    printParenthesis(1, n - 1, n, bracket);
    print("\nOptimal Cost is :", m[1][n - 1]);
   
# Driver code
arr = [ 40, 20, 30, 10, 30 ];
n = len(arr);
matrixChainOrder(arr, n);
 
# This code is contributed by phasing17


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
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


Javascript




<script>
// javascript program to print optimal parenthesization
// in matrix chain multiplication.
 
  var name=0;
 
  // Function for printing the optimal
  // parenthesization of a matrix chain product
  function printParenthesis(i , j, n, bracket)
  {
     
    // If only one matrix left in current segment
    if (i == j)
    {
      document.write(name++);
      return;
    }
    document.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);
    document.write(")");
  }
 
  // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
  // Please refer below article for details of this
  // function
  function matrixChainOrder( p , 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
         */
    var m = Array(n).fill(0).map(x => Array(n).fill(0));
 
    // bracket[i][j] stores optimal break point in
    // subexpression from i to j.
    var bracket = Array(n).fill(0).map(x => Array(n).fill(0));
 
    /*
         * 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 (var i = 1; i < n; i++)
      m[i][i] = 0;
 
    // L is chain length.
    for (var L = 2; L < n; L++)
    {
      for (var i = 1; i < n - L + 1; i++)
      {
        var j = i + L - 1;
        m[i][j] = Number.MAX_VALUE;
        for (var k = i; k <= j - 1; k++)
        {
 
          // q = cost/scalar multiplications
          var 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';
    document.write("Optimal Parenthesization is : ");
    printParenthesis(1, n - 1, n, bracket);
    document.write("\nOptimal Cost is : " + m[1][n - 1]);
  }
 
  // Driver code
  var arr = [ 40, 20, 30, 10, 30 ];
  var n = arr.length;
  matrixChainOrder(arr, n);
 
// This code is contributed by 29AjayKumar
</script>


Output

Optimal Parenthesization is : ((A(BC))D)
Optimal Cost is : 26000

Time Complexity: O(n3) 
Auxiliary Space: O(n2)

Another Approach:

This solution try to solve the problem using Recursion using permutations.

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

Let’s divide that into a Matrix

[ [40, 20], [20, 30], [30, 10], [10, 30] ]

[ A , B , C , D ]

it contains 4 matrices i.e. (n - 1)

We have 3 combinations to multiply  i.e.  (n-2)

AB    or    BC    or     CD

Algorithm:

1) Given array of matrices with length M, Loop through  M – 1 times

2) Merge consecutive matrices in each loop

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) Merge the current two matrices into one, and remove merged matrices list from list.

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) Repeat: Go to STEP – 1  with  newMatrices as input M — recursion

5) Stop recursion, when we get 2 matrices in the list.

Workflow

Matrices are reduced in following way, 

and cost’s must be retained and summed-up during recursion with previous values of each parent step.

[ 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..

on return i.e. at final step of each recursion, check if  this value smaller than of any other.

Below is JAVA,c# and Javascript implementation of above steps.

C++




#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
using namespace std;
 
// FinalCost class stores the final label and cost of the
// optimal solution
class FinalCost {
public:
    string label = "";
    int cost = INT_MAX;
};
 
class MatrixMultiplyCost {
public:
    // Recursive function that finds the optimal cost and
    // label
   
    void optimalCost(int** matrices, string* labels,
                     int prevCost, FinalCost& finalCost,
                     int len)
    {
        // Base case: If there are no or only one matrix,
        // the cost is 0 and there is no need for a label
        if (len < 2) {
            finalCost.cost = 0;
            return;
        }
       
        // Base case: If there are only two matrices, the
        // cost is the product of their dimensions and the
        // label is the concatenation of their labels
        else if (len == 2) {
            int cost = prevCost
                       + (matrices[0][0] * matrices[0][1]
                          * matrices[1][1]);
            if (cost < finalCost.cost) {
                finalCost.cost = cost;
                finalCost.label
                    = "(" + labels[0] + labels[1] + ")";
            }
            return;
        }
       
        // Iterate through all possible matrix combinations
        for (int i = 0; i < len - 1; i++) {
            int j;
           
            // Create new matrices and labels after merging
            // two matrices
            int** newMatrix = new int*[len - 1];
            string* newLabels = new string[len - 1];
            int subIndex = 0;
           
            // Calculate the cost of merging matrices[i] and
            // matrices[i+1]
            int cost = (matrices[i][0] * matrices[i][1]
                        * matrices[i + 1][1]);
           
            // Copy over the matrices and labels before the
            // merge
            for (j = 0; j < i; j++) {
                newMatrix[subIndex] = matrices[j];
                newLabels[subIndex++] = labels[j];
            }
           
            // Add the merged matrix and label
            newMatrix[subIndex] = new int[2];
            newMatrix[subIndex][0] = matrices[i][0];
            newMatrix[subIndex][1] = matrices[i + 1][1];
            newLabels[subIndex++]
                = "(" + labels[i] + labels[i + 1] + ")";
           
            // Copy over the matrices and labels after the
            // merge
            for (j = i + 2; j < len; j++) {
                newMatrix[subIndex] = matrices[j];
                newLabels[subIndex++] = labels[j];
            }
           
            // Recursively call the function with the new
            // matrices and labels
            optimalCost(newMatrix, newLabels,
                        prevCost + cost, finalCost,
                        len - 1);
        }
    }
    
    FinalCost findOptionalCost(int* arr, int len)
    {
       
        // Create matrices and labels from the input array
        int** matrices = new int*[len - 1];
        string* labels = new string[len- 1];
        for (int i = 0; i < len - 1; i++) {
            matrices[i] = new int[2];
            matrices[i][0] = arr[i];
            matrices[i][1] = arr[i + 1];
            labels[i] = char(
                65 + i); // Assign labels as A, B, C, etc.
        }
        FinalCost finalCost;
       
        // Call the recursive function to find the optimal
        // cost and label
        optimalCost(matrices, labels, 0, finalCost,
                    len - 1);
        return finalCost;
    }
};
 void printMatrix(int ** matrices, int len) {
        cout << "matrices = " << endl << "[";
        for (int i = 0; i < len; i++) {
            cout << "[" << matrices[i][0] << " " << matrices[i][1] << "]" << " ";
        }
        cout << "]" << endl;
    }
 
int main() {
    MatrixMultiplyCost calc;
 
    int arr[] = {40, 20, 30, 10, 30};
    int len = sizeof(arr) / sizeof(arr[0]);
    int **matrices = new int*[len - 1];
    string *labels = new string[len - 1];
 
    for (int i = 0; i < len - 1; i++) {
        matrices[i] = new int[2];
        matrices[i][0] = arr[i];
        matrices[i][1] = arr[i + 1];
        labels[i] = char(65 + i);
    }
 
    printMatrix(matrices, len-1);
 
    FinalCost cost = calc.findOptionalCost(arr, len);
    cout << "Final labels: \n" << cost.label << endl;
    cout << "Final Cost:\n" << cost.cost << endl;
 
    return 0;
}
 
// This code is contributed by lokeshpotta20.


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


Python3




# Python3 code to implement the approach
 
class FinalCost:
    def __init__(self):
        self.label = ""
        self.cost = float("inf")
 
def optimalCost(matrices, labels, prevCost, finalCost):
    length = len(matrices)
    if length < 2:
        finalCost.cost = 0
    elif length == 2:
        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] + ")"
    else:
        # recursive Reduce
        for i in range(length - 1):
            newMatrix = [[0] * 2 for i in range(length - 1)]
            newLabels = [0] * (length - 1)
            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
            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 in range(i):
                newMatrix[subIndex] = matrices[j]
                newLabels[subIndex] = labels[j]
                subIndex += 1
             
            newMatrix[subIndex][0] = matrices[i][0];
            newMatrix[subIndex][1] = matrices[i + 1][1];
            newLabels[subIndex] = "(" + str(labels[i]) + str(labels[i + 1]) + ")";
            subIndex+= 1
             
            for j in range(i + 2, length):
                newMatrix[subIndex] = matrices[j];
                newLabels[subIndex] = labels[j];
                subIndex+= 1
            optimalCost(newMatrix, newLabels, prevCost + cost, finalCost);
 
             
def findOptionalCost(arr):
    # STEP -1 : Prepare and convert inout as Matrix
    matrices = [[0] * 2 for i in range(len(arr) - 1)]
    labels = [0] * (len(arr) - 1)
 
    for i in range(len(arr) - 1):
        matrices[i][0] = arr[i]
        matrices[i][1] = arr[i + 1]
        labels[i] = chr(65 + i)
     
    print("matrices =", matrices)
     
     
    finalCost = FinalCost()
    optimalCost(matrices, labels, 0, finalCost)
 
    return finalCost
 
# Driver Code
 
# ======= *** TEST CASES **** ============
 
arr = [40, 20, 30, 10, 30]
 
 
cost = findOptionalCost(arr)
print("Final labels:" + cost.label)
print("Final Cost:" + str(cost.cost))
 
 
 
# This code is contributed by phasing17


C#




using System;
using System.Collections.Generic;
 
public class Cost
{
    public string label = "";
    public int cost =Int32.MaxValue;
}
 
public class MatrixMultiplyCost {
 
    private void optimalCost(int[][] matrices,
                             string[] labels, int prevCost,
                             Cost Cost)
    {
        int len = matrices.Length;
 
        if (len < 2)
        {
            Cost.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 < Cost.cost)
            {
                Cost.cost = cost;
                Cost.label
                    = "(" + labels[0]
                    + labels[1] + ")";
            }
            return;
        }
 
        // recursive Reduce
        for (int i = 0; i < len - 1; i++)
        {
            int j;
            int[][] newMatrix = new int[len - 1][];
             
            for (int x = 0; x < len - 1; x++)
                newMatrix[x] = new int[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, Cost);
        }
    }
 
    public Cost findOptionalCost(int[] arr)
    {
        // STEP -1 : Prepare and convert inout as Matrix
        int[][] matrices = new int[arr.Length - 1][];
        string[] labels = new string[arr.Length - 1];
 
        for (int i = 0; i < arr.Length - 1; i++) {
            matrices[i] = new int[2];
            matrices[i][0] = arr[i];
            matrices[i][1] = arr[i + 1];
            labels[i] = Convert.ToString((char)(65 + i));
        }
        printMatrix(matrices);
 
        Cost Cost = new Cost();
        optimalCost(matrices, labels, 0, Cost);
 
        return Cost;
    }
 
    /**
     * Driver Code
     */
    public static void Main(string[] args)
    {
        MatrixMultiplyCost calc = new MatrixMultiplyCost();
 
        // ======= *** TEST CASES **** ============
 
        int[] arr = { 40, 20, 30, 10, 30 };
        Cost cost = calc.findOptionalCost(arr);
        Console.WriteLine(" labels: \n" + cost.label);
        Console.WriteLine(" Cost:\n" + cost.cost
                           + "\n");
    }
 
    /**
     * Ignore this method
     * - THIS IS for DISPLAY purpose only
     */
    private static void printMatrix(int[][] matrices)
    {
        Console.Write("matrices = \n[");
        foreach (int[] row in matrices) {
            Console.Write("[ " + string.Join(" ", row) + " " + "], ");
        }
        Console.WriteLine("]");
    }
}
 
// This code is contributed by phasing17


Javascript




class FinalCost {
        constructor() {
          this.label = "";
          this.cost = Number.MAX_VALUE;
        }
      }
 
      function optimalCost(matrices, labels, prevCost, finalCost) {
        var len = matrices.length;
        if (len < 2) {
          finalCost.cost = 0;
          return;
        } else if (len == 2) {
          var 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 (var i = 0; i < len - 1; i++) {
          var j;
          let newMatrix = Array.from(Array(len - 1), () => new Array(2));
          let newLabels = new Array(len - 1);
          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
          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);
        }
      }
 
      function findOptionalCost(arr) {
        // STEP -1 : Prepare and convert inout as Matrix
        let matrices = Array.from(Array(arr.length - 1), () => new Array(2));
        let labels = new Array(arr.length - 1);
 
        for (var i = 0; i < arr.length - 1; i++) {
          matrices[i][0] = arr[i];
          matrices[i][1] = arr[i + 1];
          labels[i] = String.fromCharCode(65 + i);
        }
        printMatrix(matrices);
 
        let finalCost = new FinalCost();
        optimalCost(matrices, labels, 0, finalCost);
 
        return finalCost;
      }
 
      /**
       * Driver Code
       */
 
      // ======= *** TEST CASES **** ============
 
      var arr = [40, 20, 30, 10, 30];
      cost = findOptionalCost(arr);
      console.log("Final labels:" + cost.label);
      console.log("Final Cost:" + cost.cost);
 
      /**
       * Ignore this method
       * - THIS IS for DISPLAY purpose only
       */
      function printMatrix(matrices) {
        console.log("matrices = ");
        for (var k = 0; k < matrices.length; k++) {
          console.log(matrices[k]);
        }
      }
       
      // This code is contributed by satwiksuman.


Output

matrices = 
[[40 20] [20 30] [30 10] [10 30] ]
Final labels: 
((A(BC))D)
Final Cost:
26000

Time Complexity : O(n2)

Auxiliary Space:O(n2)



Previous Article
Next Article

Similar Reads

Printing Matrix Chain Multiplication (A Space Optimized Solution)
Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices be
12 min read
Matrix Chain Multiplication (A O(N^2) Solution)
Given an array p[] of size n, which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[I], Where i is in the range of 1 to n - 1. The task is to find the minimum number of multiplications needed to multiply the chain. Example: Input: p[] = {40, 20, 30, 10, 30} Output: 26000 Explanation: There are 4 matrices of d
9 min read
Matrix Chain Multiplication | DP-8
Given the dimension of a sequence of matrices in an array arr[], where the dimension of the ith matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. Examples: Input: arr[] = {40, 20, 30, 10, 30}Output: 26000Explanation:There ar
15+ min read
Printing Longest Common Subsequence | Set 2 (Printing All)
Given two sequences, print all longest subsequence present in both of them.Examples: Input: string X = "AGTGATG" string Y = "GTTAG" Output: GTAG GTTG Input: string X = "AATCC" string Y = "ACACG" Output: ACC AAC Input: string X = "ABCBDAB" string Y = "BDCABA" Output: BCAB BCBA BDAB We have discussed Longest Common Subsequence (LCS) problem here. The
12 min read
Printing all solutions in N-Queen Problem
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 4 Queen problem. In previous post, we have discussed an approach that prints only one possible solution, so now in this post, the task is to print all solutions in N-Queen Problem. Each solu
15+ min read
Encode given String by inserting in Matrix column-wise and printing it row-wise
Given a string S and an integer R, the task is to encode the string by first filling each character in column wise manner from top to bottom in a matrix having R rows and then printing the matrix row-wise. Examples: Input: S = "abcdefgh", R = 3Output: adgbehcfExplanation: Matrix formed is:a d gb e hc fSo when printed row wise it gives the encoded s
4 min read
Printing string in plus ‘+’ pattern in the matrix
Given a string, print it inside a matrix in such a way that a 'plus' is formed. Examples: Input: TOP Output: X T X T O P X P X Input: FEVER Output: X X F X X X X E X X F E V E R X X E X X X X R X X Approach: The idea is simple. First we can access every element of the matrix and make it ‘X’. Then we will insert the characters of the string in the m
10 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Binary tree to string with brackets
Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". Omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Examples: Input : Preorder: [1,
8 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 &lt;= length(position[]) &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Balance a string after removing extra brackets
Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it. Examples: Input: str = "gau)ra)v(ku(mar(rajput))" Output: gaurav(ku(mar(rajput))) Input: str = "1+5)+5+)6+(5+9)*9" Output: 1+5+5+6+(5+9)*9 Approach: Start traversing from left to right.Check if the element at current inde
6 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times
Given a string S of size N consisting of only '(' and ')' only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times. Examples: Input: S = ")(", K = 1Output: YesExplanation: Move S[0] to the end of the
8 min read
Minimum swaps to balance the given brackets at any index
Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represented in the form of "[S1]" where S1 is a balanced
5 min read
Print all Balanced Brackets Strings that can be formed by replacing wild card '?'
Given string str containing characters '?', '(' and ')', the task is to replace the '?' character with '(' or ')' and print all the strings containing balanced brackets Example: Input: str = "????"Output:()()(()) Input: str = "(()?"Output: (()) Approach: The given problem can be solved using recursion and backtracking. The idea is to substitute eve
10 min read
Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
Given an expression string exp, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp. Example:  Input: exp = "[()]{}{[()()]()}" Output: Balanced Input: exp = "[(])" Output: Not Balanced  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
Balanced expressions such that given positions have opening brackets
Given an integer n and an array of positions 'position[]' (1 &lt;= position[i] &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have opening bracket.Examples : Input : n = 3, position[] = [2}Output : 3 Explanation : The proper bracket sequences of length 6 and opening bracket
15 min read
Find an equal point in a string of brackets
Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. '(' and ')'. An equal point is an index such that the number of opening brackets before it is equal to the number of closing bracket
14 min read
Remove brackets from an algebraic string containing + and - operators
Simplify a given algebraic string of characters, '+', '-' operators and parentheses. Output the simplified string without parentheses. Examples: Input : "(a-(b+c)+d)" Output : "a-b-c+d" Input : "a-(b-c-(d+e))-f" Output : "a-b+c+d+e-f" The idea is to check operators just before starting of bracket, i.e., before character '('. If operator is -, we ne
8 min read
Check if two expressions with brackets are same
Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'. Examples: Input : exp1 = "-(a+b+c)" exp2 = "-a-b-c" Output : Yes Input : exp1 = "-(c+b+a)" exp2 = "-c-b-a" Output : Yes Input : exp1 = "a-b-(c-d)" exp2 = "a-b-c-d" Output : No It ma
11 min read
Check for Balanced Brackets in an expression (well-formedness)
Given an expression string exp, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in the given expression. Example:  Input: exp = "[()]{}{[()()]()}" Output: BalancedExplanation: all the brackets are well-formed Input: exp = "[(])" Output: Not Balanced Explanation: 1 and 4 brackets are not balanc
12 min read
Program for scalar multiplication of a matrix
Given a matrix and a scalar element k, our task is to find out the scalar product of that matrix. Examples: Input : mat[][] = {{2, 3} {5, 4}} k = 5 Output : 10 15 25 20 We multiply 5 with every element. Input : 1 2 3 4 5 6 7 8 9 k = 4 Output : 4 8 12 16 20 24 28 32 36 The scalar multiplication of a number k(scalar), multiply it on every entry in th
6 min read
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Given two square matrices A and B of size n x n each, find their multiplication matrix. Naive Method: Following is a simple way to multiply two matrices. C/C++ Code void multiply(int A[][N], int B[][N], int C[][N]) { for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt; N; j++) { C[i][j] = 0; for (int k = 0; k &lt; N; k++) { C[i][j] += A[i][k]*B[
15+ min read
Matrix Multiplication | Recursive
Given two matrices A and B. The task is to multiply matrix A and matrix B recursively. If matrix A and matrix B are not multiplicative compatible, then generate output "Not Possible". Examples : Input: A = 12 56 45 78 B = 2 6 5 8Output: 304 520 480 894Input: A = 1 2 3 4 5 6 7 8 9 B = 1 2 3 4 5 6 7 8 9Output: 30 36 42 66 81 96 102 126 150 It is reco
9 min read
Multiplication of Matrix using threads
Multiplication of matrix does take time surely. Time complexity of matrix multiplication is O(n^3) using normal matrix multiplication. And Strassen algorithm improves it and its time complexity is O(n^(2.8074)). But, Is there any way to improve the performance of matrix multiplication using the normal method.  Multi-threading can be done to improve
15 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
three90RightbarBannerImg