forked from riya2001-cloud/java-hacktober
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrixchain.cpp
52 lines (42 loc) · 1.32 KB
/
matrixchain.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
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Function to find the most efficient way to multiply
// a given sequence of matrices
int matrixChainMultiplication(vector<int> const &dims)
{
int n = dims.size();
// c[i, j] = Minimum number of scalar multiplications (i.e., cost)
// needed to compute matrix `M[i] M[i+1] … M[j] = M[i…j]`
// The cost is zero when multiplying one matrix
int c[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
c[i][i] = 0;
}
for (int len = 2; len <= n; len++) // subsequence lengths
{
for (int i = 1; i <= n - len + 1; i++)
{
int j = i + len - 1;
c[i][j] = INT_MAX;
for (int k = i; j < n && k <= j - 1; k++)
{
int cost = c[i][k] + c[k + 1][j] + dims[i - 1] * dims[k] * dims[j];
if (cost < c[i][j]) {
c[i][j] = cost;
}
}
}
}
return c[1][n - 1];
}
// Matrix Chain Multiplication Problem
int main()
{
// Matrix `M[i]` has dimension `dims[i-1] × dims[i]` for `i=1…n`
// input is 10 × 30 matrix, 30 × 5 matrix, 5 × 60 matrix
vector<int> dims = { 10, 30, 5, 60 };
cout << "The minimum cost is " << matrixChainMultiplication(dims);
return 0;
}