-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_MatrixChainMultiplication.cpp
124 lines (104 loc) · 2.92 KB
/
GFG_MatrixChainMultiplication.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
https://practice.geeksforgeeks.org/problems/matrix-chain-multiplication0303/1#
Matrix Chain Multiplication
*/
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution{
public:
vector<vector<int>> memo;
vector<vector<int>> paren;
int matrixMultiplication(int N, int arr[])
{
int numMat = N-1;
memo.resize(numMat+2, vector<int>(numMat+2, -1));
paren.resize(numMat+2, vector<int>(numMat+2, 0));
/*
// N is dimension of dimensions matrix
// N-1 (numMat) is the number of matrices
// N-2 is the index of last matrix
solve(0, numMat-1, arr);
*/
for(int i=0; i<numMat; i++)
memo[i][i] = 0;
for(int len = 2; len<=numMat; len++) // moving diagonally
{
for(int i=0; i<numMat-len +1 ; i++) // first matrix index
{
int j = i + len - 1; // last matrix index
int val=INT_MAX;
for(int k=i; k<j; k++)
{
int curval = memo[i][k] + memo[k+1][j] + arr[i]*arr[k+1]*arr[j+1];
if(curval < val)
{
val = curval;
paren[i][j] = k;
}
}
memo[i][j] = val;
}
}
// for(int i=0; i<numMat; i++)
// {
// for(int j=0; j< numMat; j++)
// {
// cout<<memo[i][j]<<", "<<paren[i][j]<<"| ";
// }
// cout<<endl;
// }
// print_optimal_parens(0, numMat-1);
// cout<<endl;
return memo[0][numMat-1];
}
void print_optimal_parens(int i, int j)
{
if(i==j)
cout<<"A"<<i;
else
{
cout<<"(";
print_optimal_parens(i, paren[i][j]);
cout<<".";
print_optimal_parens(paren[i][j]+1, j);
cout<<")";
}
}
int solve(int i, int j, int *d)
{
if(i==j)
return memo[i][j]=0;
if(memo[i][j] != -1)
return memo[i][j];
int val = INT_MAX;
for(int k=i; k<j; k++)
{
int curval = solve(i, k, d) + solve(k+1, j, d) + d[i]*d[k+1]*d[j+1];
if(curval < val)
{
val = curval;
paren[i][j] = k;
}
}
return memo[i][j]=val;
}//int
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N;
cin>>N;
int arr[N];
for(int i = 0;i < N;i++)
cin>>arr[i];
Solution ob;
cout<<ob.matrixMultiplication(N, arr)<<endl;
}
return 0;
} // } Driver Code Ends