-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDay8.cpp
64 lines (56 loc) · 1.59 KB
/
Day8.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
//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:
void genAns(int st, int end,vector< string >& ans, vector< vector<int> >& divn){
if(end-st == 0)
return ;
genAns(st,divn[st][end],ans,divn) ;
genAns(divn[st][end]+1,end,ans,divn) ;
ans[st] = "(" + ans[st] ;
ans[end] = ans[end] + ")" ;
}
string matrixChainOrder(int p[], int n){
vector< vector<int> > dp(n-1, vector<int>(n-1)), divn(n-1, vector<int>(n-1,-1)) ;
for(int size=2 ; size<=n-1 ; size++){
for(int st=0 ; st+size-1 <= n-2 ; st++){
dp[st][st+size-1] = INT_MAX ;
for(int k=st ; k<st+size-1 ; k++){
if(dp[st][st+size-1] > p[st]*p[k+1]*p[st+size] + dp[st][k] + dp[k+1][st+size-1]){
dp[st][st+size-1] = p[st]*p[k+1]*p[st+size] + dp[st][k] + dp[k+1][st+size-1] ;
divn[st][st+size-1] = k ;
}
}
}
}
vector< string > ans(n-1) ;
for(int i=0 ; i<n-1 ; i++){
ans[i] = 'A'+i ;
}
genAns(0,n-2,ans,divn) ;
string fans ;
for(int i=0 ; i<n-1 ; i++)
fans += ans[i] ;
return fans ;
}
};
// { 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