forked from gaurav03kr/hello-hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix_chain_multiplication.cpp
47 lines (39 loc) · 1.03 KB
/
matrix_chain_multiplication.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
/*
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.
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]).
*/
/* A naive recursive implementation that simply
follows the above optimal substructure property */
#include <bits/stdc++.h>
using namespace std;
// Matrix Ai has dimension p[i-1] x p[i]
// for i = 1..n
int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;
int k;
int min = INT_MAX;
int count;
for (k = i; k < j; k++)
{
count = MatrixChainOrder(p, i, k)
+ MatrixChainOrder(p, k + 1, j)
+ p[i - 1] * p[k] * p[j];
if (count < min)
min = count;
}
// Return minimum count
return min;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum number of multiplications is "
<< MatrixChainOrder(arr, 1, n - 1);
}