forked from piyush-kash/Hacktober2021-cpp-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_chain_multiplication.cpp
More file actions
48 lines (41 loc) · 1.01 KB
/
matrix_chain_multiplication.cpp
File metadata and controls
48 lines (41 loc) · 1.01 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
// { 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:
int matrixMultiplication(int n, int arr[])
{
int dp[n][n];
for(int i=0; i<n; i++){
dp[i][i] = 0;
}
for(int len = 2; len < n; len++){
for(int i=1; i <= n-len; i++){
int j = i + len - 1;
dp[i][j] = INT_MAX;
for(int k = i; k<j; k++){
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + arr[i-1]*arr[j]*arr[k]);;
}
}
}
return dp[1][n-1];
}
};
// { 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