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 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 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
This problem is mainly an extension of Finding Optimal cost of Matrix Chain Multiplication . Here we also need to print brackets.
We have discussed a solution in a post that uses two matrices. In this post, a space-optimized solution is discussed that uses a single matrix.
1) To find the optimal cost, we create a matrix whose only upper triangle is filled and the rest of the cells are not used.
2) The idea is to use the lower triangular part of the same matrix (that is not used) for storing brackets.
The idea is to store optimal break point for every subexpression (i, j) at m [ j ][ i ] and optimal cost at m [ i ] [ j ].
Below is the implementation of above steps.
C++
#include<bits/stdc++.h>
using namespace std;
void printParenthesis( int i, int j, int n,
int *bracket, char &name)
{
if (i == j)
{
cout << name++;
return ;
}
cout << "(" ;
printParenthesis(i, *((bracket+j*n)+i), n,
bracket, name);
printParenthesis(*((bracket+j*n)+i) + 1, j,
n, bracket, name);
cout << ")" ;
}
void matrixChainOrder( int p[], int n)
{
int m[n][n];
for ( int i=1; i<n; i++)
m[i][i] = 0;
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++)
{
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;
m[j][i] = k;
}
}
}
}
char name = 'A' ;
cout << "Optimal Parenthesization is: " ;
printParenthesis(1, n-1, n, ( int *)m, name);
cout << "\nOptimal Cost is : " << m[1][n-1];
}
int main()
{
int arr[] = {40, 20, 30, 10, 30};
int n = sizeof (arr)/ sizeof (arr[0]);
matrixChainOrder(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static char name;
static void printParenthesis( int i, int j, int n, int [][] bracket)
{
if (i == j)
{
System.out.print(name++);
return ;
}
System.out.print( '(' );
printParenthesis(i, bracket[j][i], n, bracket);
printParenthesis(bracket[j][i] + 1 , j, n, bracket);
System.out.print( ')' );
}
static void matrixChainOrder( int [] p, int n)
{
int [][] m = new int [n][n];
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++)
{
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;
m[j][i] = k;
}
}
}
}
name = 'A' ;
System.out.print( "Optimal Parenthesization is: " );
printParenthesis( 1 , n - 1 , n, m);
System.out.print( "\nOptimal Cost is :" + m[ 1 ][n - 1 ]);
}
public static void main(String[] args)
{
int [] arr = { 40 , 20 , 30 , 10 , 30 };
int n = arr.length;
matrixChainOrder(arr, n);
}
}
|
Python3
def printParenthesis(m, j, i ):
if j = = i:
print ( chr ( 65 + j), end = "")
return ;
else :
print ( "(" , end = "")
printParenthesis(m, m[j][i] - 1 , i)
printParenthesis(m, j, m[j][i])
print ( ")" , end = "" )
def matrixChainOrder(p, n):
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
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
m[j][i] = k + 1
return m;
arr = [ 40 , 20 , 30 , 10 , 30 ]
n = len (arr) - 1
m = matrixChainOrder(arr, n)
print ( "Optimal Parenthesization is: " , end = "")
printParenthesis(m, n - 1 , 0 )
print ( "\nOptimal Cost is :" , m[ 0 ][n - 1 ])
|
C#
using System;
class GFG{
static char name;
static void printParenthesis( int i, int j,
int n, int [,] bracket)
{
if (i == j)
{
Console.Write(name++);
return ;
}
Console.Write( '(' );
printParenthesis(i, bracket[j, i], n, bracket);
printParenthesis(bracket[j, i] + 1, j, n, bracket);
Console.Write( ')' );
}
static void matrixChainOrder( int [] p, int n)
{
int [,] m = new int [n, n];
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++)
{
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;
m[j, i] = k;
}
}
}
}
name = 'A' ;
Console.Write( "Optimal Parenthesization is: " );
printParenthesis(1, n - 1, n, m);
Console.Write( "\nOptimal Cost is :" + m[1, n - 1]);
}
public static void Main(String[] args)
{
int [] arr = { 40, 20, 30, 10, 30 };
int n = arr.Length;
matrixChainOrder(arr, n);
}
}
|
Javascript
<script>
function printParenthesis(m, j, i){
if (j == i){
document.write(String.fromCharCode(65 + j), end = "" )
return ;
}
else {
document.write( "(" , end = "" )
printParenthesis(m, m[j][i] - 1, i)
printParenthesis(m, j, m[j][i])
document.write( ")" )
}
}
function matrixChainOrder(p, n){
let m = new Array(n).fill(0).map(()=> new Array(n).fill(0))
for (let l=2;l<n + 1;l++){
for (let i=0;i<(n - l + 1);i++){
let j = i + l - 1
m[i][j] = Number.MAX_VALUE
for (let k=i;k<j;k++){
let 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
m[j][i] = k + 1
}
}
}
}
return m;
}
let arr = [40, 20, 30, 10, 30]
let n = arr.length - 1
let m = matrixChainOrder(arr, n)
document.write( "Optimal Parenthesization is: " )
printParenthesis(m, n - 1, 0)
document.write( "</br>" , "Optimal Cost is :" , m[0][n - 1])
</script>
|
Output:
Optimal Parenthesization is : ((A(BC))D)
Optimal Cost is : 26000
Time Complexity: O(n^3)
Auxiliary Space: O(n^2): The asymptotic value remains same, but we reduce the auxiliary space to half.
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...