Skip to content

Instantly share code, notes, and snippets.

@bruceoutdoors
Last active November 17, 2015 13:03
Show Gist options
  • Save bruceoutdoors/7a454c81cb36e99d4f08 to your computer and use it in GitHub Desktop.
Save bruceoutdoors/7a454c81cb36e99d4f08 to your computer and use it in GitHub Desktop.
Matrix Chain Multiplication recursive solution
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;
vector<int> rc;
int B(int i, int j)
{
if (i == j) return 0;
int mink = INT_MAX;
for (int k = i; k < j; k++) {
mink = min(mink, B(i, k) + B(k+1, j) + rc[i]*rc[k+1]*rc[j+1]);
}
return mink;
}
int main()
{
int c; cin >> c;
rc = vector<int>(c+1, -1);
int x;
// for every matrix i, rc[i] is row and rc[i+1] is column.
for (int i = 1; i <= c; i++) {
cin >> x;
rc[i] = x;
}
int n = c - 1;
cout << B(1, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment