You are on page 1of 2

Experiment-14

Aim: 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.

Algorithm:

QUICKSORT (array A, start, end)


{
1 if (start < end)
2{
3 p = partition(A, start, end)
4 QUICKSORT (A, start, p - 1)
5 QUICKSORT (A, p + 1, end)
6}
}

Code:

#include <bits/stdc++.h>
using namespace std;
int MinCost(int arr[],int n)
{
int dp[n][n];
memset(dp,0,sizeof(dp));
int i,j,k;
int mi;
for(i=1;i<n-1;i++)
{
dp[2][i] = arr[i-1]*arr[i]*arr[i+1];
}
for(i=3;i<n;i++)
{
for(j=1;j<=n-i;j++)
{
mi = INT_MAX;
int x,y;
for(k=j;k<j+i-1;k++)
{
x = dp[k-j+1][j];
y = dp[(j+i-1)-k][k+1];
mi = min(mi,x+y+arr[j-1]*arr[k]*arr[j+i-1]);
}
dp[i][j] = mi;
}
}
return dp[n-1][1];
}

int main() {
//code
int t,n,i;
cin>>t;
while(t--)
{
cin>>n;
int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<MinCost(a,n)<<endl;
}
return 0;
}

Output:

You might also like