Skip to content

Commit e1f6af1

Browse files
authored
Merge pull request #5 from SunmeetOberoi/matrix-chain-multiplication
Added Matrix-chain multiplication
2 parents 1236960 + ab40f03 commit e1f6af1

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#include<iostream>
2+
#include<vector>
3+
4+
using namespace std;
5+
6+
// Bottom-Up
7+
int** matrix_chain_order(vector<int> p) {
8+
9+
// size
10+
int n = p.size() - 1;
11+
12+
// declaring and intialising result matrices
13+
int** s = new int* [n];
14+
int** m = new int* [n + 1];
15+
for (int i = 0;i < n;i++) {
16+
s[i] = new int[n + 1];
17+
m[i] = new int[n + 1];
18+
m[i][i] = 0;
19+
}
20+
m[n] = new int[n + 1];
21+
m[n][n] = 0;
22+
23+
// calculating order
24+
int q;
25+
for (int l = 2;l <= n;l++) {
26+
for (int i = 1;i <= n - l + 1;i++) {
27+
int j = i + l - 1;
28+
m[i][j] = INT_MAX;
29+
for (int k = i;k < j;k++) {
30+
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
31+
if (q < m[i][j]) {
32+
m[i][j] = q;
33+
s[i][j] = k;
34+
}
35+
}
36+
}
37+
}
38+
return s;
39+
}
40+
41+
void print_optimal_parens(int** s, int i, int j) {
42+
if (i == j)
43+
cout << "A" << i;
44+
else {
45+
46+
cout << "(";
47+
print_optimal_parens(s, i, s[i][j]);
48+
print_optimal_parens(s, s[i][j] + 1, j);
49+
cout << ")";
50+
}
51+
}
52+
53+
54+
// Top-Down
55+
int lookup_chain(int** m, vector<int> p, int i, int j) {
56+
if (m[i][j] < INT_MAX)
57+
return m[i][j];
58+
if (i == j)
59+
m[i][j] = 0;
60+
else {
61+
int q;
62+
for (int k = i;k <= j - 1;k++) {
63+
q = lookup_chain(m, p, i, k) + lookup_chain(m, p, k + 1, j) + p[i - 1] * p[k] * p[j];
64+
if (q < m[i][j])
65+
m[i][j] = q;
66+
}
67+
}
68+
return m[i][j];
69+
}
70+
71+
int memoized_matrix_chain(vector<int> p) {
72+
int n = p.size() - 1;
73+
74+
int** m = new int*[n + 1];
75+
for (int i = 0;i <= n;i++) {
76+
m[i] = new int[n + 1];
77+
for (int j = 0;j <= n;j++) {
78+
m[i][j] = INT_MAX;
79+
}
80+
}
81+
return lookup_chain(m, p, 1, n);
82+
}
83+
84+
85+
int main() {
86+
vector<int> p;
87+
int n;
88+
cout << "Enter number of matrices to multiply: ";
89+
cin >> n;
90+
int temp;
91+
for (int i = 0;i <= n;i++) {
92+
cin >> temp;
93+
p.push_back(temp);
94+
}
95+
print_optimal_parens(matrix_chain_order(p), 1, n);
96+
cout << endl << "Total Calculations: " << memoized_matrix_chain(p); // calculated using top-down approach
97+
return 0;
98+
}

0 commit comments

Comments
 (0)