Skip to content

Instantly share code, notes, and snippets.

@WizzyGeek
Created February 22, 2024 12:01
Show Gist options
  • Save WizzyGeek/c90bac78d6f7587607b37f52454c05c6 to your computer and use it in GitHub Desktop.
Save WizzyGeek/c90bac78d6f7587607b37f52454c05c6 to your computer and use it in GitHub Desktop.
Matrix Chain Multiplication - The easy somewhat modern C++
#include<iostream>
#include<vector>
#include<climits>
#include<string>
// MCM
std::string make_exp(std::vector<std::vector<int>> &s, int i, int j) {
if (i == j) {
return std::string(1, 'A' + i - 1);
}
return "(" + make_exp(s, i, s[i][j]) + make_exp(s, s[i][j] + 1, j) + ")";
}
int main() {
int n;
std::cin >> n >> n;
std::vector<int> p(n, 0);
for (int i = 0; i < n; i++) std::cin >> p[i];
// for (int k : p) std::cout << k;
std::vector<std::vector<int>> c(n, std::vector<int>(n, 0));
std::vector<std::vector<int>> s(n, std::vector<int>(n, 0));
for (int l = 2; l < n; l++) {
for (int i = 1; i <= n - l; i++) {
int j = i + l - 1;
int mk = -1;
int m = INT_MAX;
for (int k = i; k < j; k++) {
int cost = p[i - 1] * p[k] * p[j] + c[i][k] + c[k + 1][j];
if (cost < m) {
mk = k;
m = cost;
}
}
c[i][j] = m;
s[i][j] = mk;
}
}
std::cout << c[1][n - 1] << '\n';
std::cout << make_exp(s, 1, n-1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment