|  | 
|  | 1 | +#include <climits> | 
|  | 2 | +#include <iostream> | 
|  | 3 | +using namespace std; | 
|  | 4 | + | 
|  | 5 | +#define MAX 10 | 
|  | 6 | + | 
|  | 7 | +// dp table to store the solution for already computed sub problems | 
|  | 8 | +int dp[MAX][MAX]; | 
|  | 9 | + | 
|  | 10 | +// Function to find the most efficient way to multiply the given sequence of | 
|  | 11 | +// matrices | 
|  | 12 | +int MatrixChainMultiplication(int dim[], int i, int j) { | 
|  | 13 | + // base case: one matrix | 
|  | 14 | + if (j <= i + 1) | 
|  | 15 | + return 0; | 
|  | 16 | + | 
|  | 17 | + // stores minimum number of scalar multiplications (i.e., cost) | 
|  | 18 | + // needed to compute the matrix M[i+1]...M[j] = M[i..j] | 
|  | 19 | + int min = INT_MAX; | 
|  | 20 | + | 
|  | 21 | + // if dp[i][j] is not calculated (calculate it!!) | 
|  | 22 | + | 
|  | 23 | + if (dp[i][j] == 0) { | 
|  | 24 | + // take the minimum over each possible position at which the | 
|  | 25 | + // sequence of matrices can be split | 
|  | 26 | + | 
|  | 27 | + for (int k = i + 1; k <= j - 1; k++) { | 
|  | 28 | + // recur for M[i+1]..M[k] to get a i x k matrix | 
|  | 29 | + int cost = MatrixChainMultiplication(dim, i, k); | 
|  | 30 | + | 
|  | 31 | + // recur for M[k+1]..M[j] to get a k x j matrix | 
|  | 32 | + cost += MatrixChainMultiplication(dim, k, j); | 
|  | 33 | + | 
|  | 34 | + // cost to multiply two (i x k) and (k x j) matrix | 
|  | 35 | + cost += dim[i] * dim[k] * dim[j]; | 
|  | 36 | + | 
|  | 37 | + if (cost < min) | 
|  | 38 | + min = cost; // store the minimum cost | 
|  | 39 | + } | 
|  | 40 | + dp[i][j] = min; | 
|  | 41 | + } | 
|  | 42 | + | 
|  | 43 | + // return min cost to multiply M[j+1]..M[j] | 
|  | 44 | + return dp[i][j]; | 
|  | 45 | +} | 
|  | 46 | + | 
|  | 47 | +// main function | 
|  | 48 | +int main() { | 
|  | 49 | + // Matrix i has Dimensions dim[i-1] & dim[i] for i=1..n | 
|  | 50 | + // input is 10 x 30 matrix, 30 x 5 matrix, 5 x 60 matrix | 
|  | 51 | + int dim[] = {10, 30, 5, 60}; | 
|  | 52 | + int n = sizeof(dim) / sizeof(dim[0]); | 
|  | 53 | + | 
|  | 54 | + // Function Calling: MatrixChainMultiplications(dimensions_array, starting, | 
|  | 55 | + // ending); | 
|  | 56 | + | 
|  | 57 | + cout << "Minimum cost is " << MatrixChainMultiplication(dim, 0, n - 1) | 
|  | 58 | + << "\n"; | 
|  | 59 | + | 
|  | 60 | + return 0; | 
|  | 61 | +} | 
0 commit comments