|
| 1 | +// Matrix Chain Multiplication |
| 2 | +// Given a sequence of matrices, find the most efficient way to multiply these matrices together. The efficient way is the one that involves the least number of multiplications. |
| 3 | +// The dimensions of the matrices are given in an array arr[] of size N (such that N = number of matrices + 1) where the ith matrix has the dimensions (arr[i-1] x arr[i]). |
| 4 | +// Example 1: |
| 5 | +// Input: N = 5 |
| 6 | +// arr = {40, 20, 30, 10, 30} |
| 7 | +// Output: 26000 |
| 8 | +// Explaination: There are 4 matrices of dimension |
| 9 | +// 40x20, 20x30, 30x10, 10x30. Say the matrices are |
| 10 | +// named as A, B, C, D. Out of all possible combinations, |
| 11 | +// the most efficient way is (A*(B*C))*D. |
| 12 | +// The number of operations are - |
| 13 | +// 20*30*10 + 40*20*10 + 40*10*30 = 26000. |
| 14 | + |
| 15 | +// Example 2: |
| 16 | +// Input: N = 4 |
| 17 | +// arr = {10, 30, 5, 60} |
| 18 | +// Output: 4500 |
| 19 | +// Explaination: The matrices have dimensions |
| 20 | +// 10*30, 30*5, 5*60. Say the matrices are A, B |
| 21 | +// and C. Out of all possible combinations,the |
| 22 | +// most efficient way is (A*B)*C. The |
| 23 | +// number of multiplications are - |
| 24 | +// 10*30*5 + 10*5*60 = 4500. |
| 25 | +int dp[101][101]; |
| 26 | +int solve(int n, int arr[], int i,int j){ |
| 27 | + if(i>=j)return 0; |
| 28 | + if(dp[i][j]!=-1)return dp[i][j]; |
| 29 | + int temp=INT_MAX; |
| 30 | + for(int k=i;k<j;k++){ |
| 31 | + temp=min(temp,solve(n,arr,i,k)+solve(n,arr,k+1,j)+arr[i-1]*arr[k]*arr[j]); |
| 32 | + } |
| 33 | + dp[i][j]=temp; |
| 34 | + return temp; |
| 35 | + |
| 36 | +} |
| 37 | + int matrixMultiplication(int N, int arr[]) |
| 38 | + { |
| 39 | + memset(dp,-1, sizeof(dp)); |
| 40 | + return solve(N,arr,1,N-1); |
| 41 | + } |
0 commit comments