#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
long matrix_chain(long P[], long M[], int S[], size_t size) {
int l{};
int j{};
int i{};
int k{};
for (l = 2; l <= size; ++l) {
for (i = 0; i <= size - l; ++i) {
j = i + l - 1;
long min{ numeric_limits<long>::max() };
long min_k{ -1 };
long tmp{};
for (k = i; k < j; ++k) {
if ((tmp = M[i * size + k] + M[(k + 1) * size + j] + P[i] * P[k + 1] * P[j + 1]) < min) {
min = tmp;
min_k = k;
}
}
M[i * size + j] = min;
S[i * size + j] = min_k;
}
}
return M[size - 1];
}
void print_optimal_parens(int S[], int i, int j, size_t size) {
if (i == j) {
cout << "A" << i;
}
else {
cout << "(";
print_optimal_parens(S, i, S[i * size + j], size);
print_optimal_parens(S, S[i * size + j] + 1, j, size);
cout << ")";
}
}
int main(int argc, char* argv[]) {
vector<long> v{};
cout << "please input the matrix list : (the col of former is equal to the row of later)" << endl;
long element{};
while (cin >> element) {
v.push_back(element);
}
size_t matrix_quantity { v.size() - 1};
long* P = new long[matrix_quantity + 1] {};
long* M = new long[matrix_quantity * matrix_quantity] {};
int* S = new int[matrix_quantity * matrix_quantity] {};
int index{};
for_each(v.begin(), v.end(), [=](long x)mutable{P[index++] = x; });
long result{};
result = matrix_chain(P, M, S, matrix_quantity);
cout << "the optimal parens is :" << endl;
print_optimal_parens(S, 0, matrix_quantity - 1, matrix_quantity);
cout << "the sum of multiply is : " << result << endl;
delete[]P;
delete[]M;
delete[]S;
return 0;
}