#include<iostream>
#include<iomanip>
using namespace std;
fun(int l,int n,int m[]) {
int i,j,k,r;
int **a = new int*[n];
for(i=0;i<n;i++) {
a[i] = new int[n];
}
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
a[i][j] = 0;
}
}
for(i=0;i<n;i++) {
for(j=0,k=i;k!=n;j++,k++) {
if(j==k) a[j][k] = 0;
else {
int min = 1000000;
for(r=j;r<k;r++) {
int temp = a[j][r] + a[r+1][k] + m[j] * m[r+1] * m[k+1];
cout<<m[j] * m[r+1] * m[k]<<endl;
if(temp < min) min = temp;
}
a[j][k] = min;
cout<<j<<":"<<k<<endl;
}
}
}
return a[0][n-1];
}
int main() {
int n[] = {50,10,40,30,5};
cout<<fun(0,4,n)<<endl;
return 0;
}
<——————————————————————————————————————————————————————————————————>
#include<iostream>
using namespace std;
//运用动态规划的思想解决矩阵连乘问题
int matrixMul(int i, int j, int p[]) {
int **array;//array[i][j]
array = new int*[j + 1];
for (int k1 = 0; k1 < j + 1; k1++) {
array[k1] = new int[j + 1];
for (int k2 = 0; k2 < j + 1; k2++)
array[k1][k2] = 0;
}
for (int f = 1; f < j + 1; f++) {
for (int k1 = i, k2 = f; k1 < j + 1 && k2 < j + 1; k1++, k2++) {
int min = 100000000;
if (k1 == k2)
break;
for (int k = k1; k < k2; k++) {
int temp = array[k1][k] + array[k + 1][k2] + p[k1 - 1] * p[k] * p[k2];
if (temp < min)
min = temp;
}
array[k1][k2] = min;
}
}
return array[i][j];
}
int main() {
int p[] = { 50, 10, 40, 30, 5 };
int result = matrixMul(1, 4, p);
cout << result << endl;
return 0;
}