-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMatrix Chain Multiplication (Top down).cpp
More file actions
65 lines (62 loc) · 1.17 KB
/
Matrix Chain Multiplication (Top down).cpp
File metadata and controls
65 lines (62 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<climits>
#include<cstring>
using namespace std;
int dp[100][100];
int s[100][100];
int MCM(int arr[], int i, int j)
{
int k;
int q;
if(i == j)
return dp[i][j]=0;
if(dp[i][j] != -1)
{
return dp[i][j];
}
int minV = INT_MAX;
for(k=i; k<=j-1; k++)
{
q = MCM(arr,i,k) + MCM(arr,k+1,j)+ arr[i-1]*arr[k]*arr[j];
if(q < minV)
{
minV = q;
}
dp[i][j] = minV;
s[i][j] = k;
}
return dp[i][j];
}
int printoptimalparen(int i,int j)
{
if(i==j)
{
cout<<"A"<<i+1;
}
else
{
cout<<"(";
printoptimalparen(i,s[i][j]);
printoptimalparen(s[i][j]+1, j);
cout<<")";
}
}
int main()
{
int n,i;
cout<<"Enter number of matrices\n";
cin>>n;
n++;
int arr[n+1];
cout<<"Enter dimensions\n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
memset(dp,-1,sizeof(dp));
cout<<"Minimum number of multiplication is: "<<MCM(arr,1,n-1);
cout <<endl;
cout<<"Chain Order: ";
printoptimalparen(0,n-2);
return 0;
}