-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_MatrixChainMultiplicationBrackets.cpp
87 lines (70 loc) · 1.81 KB
/
GFG_MatrixChainMultiplicationBrackets.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
/*
https://practice.geeksforgeeks.org/problems/brackets-in-matrix-chain-multiplication1024/1#
Brackets in 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;
string ans;
string matrixChainOrder(int p[], int n)
{
int numMat = n-1;
memo.resize(numMat+2, vector<int>(numMat+2, -1));
paren.resize(numMat+2, vector<int>(numMat+2, 0));
solve(0, numMat-1, p);
print_optimal_parens(0, numMat-1);
return ans;
}
void print_optimal_parens(int i, int j)
{
if(i==j)
ans.push_back((char)i+'A');
else
{
ans.push_back('(');
print_optimal_parens(i, paren[i][j]);
print_optimal_parens(paren[i][j]+1, j);
ans.push_back(')');
}
}
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 p[n];
for(int i = 0;i < n;i++)
cin>>p[i];
Solution ob;
cout<<ob.matrixChainOrder(p, n)<<"\n";
}
return 0;
} // } Driver Code Ends