#include <bits/stdc++.h>
using namespace std;
const int N=7;
int p[N]={30, 35, 15, 5, 10, 20, 25};
void MatrixChain(int m[N][N], int s[N][N])
{
int n=N-1;//一共7个数,6个矩阵
for(int i=1; i<N; i++)
m[i][i]=0;//初始化m数组,1-6矩阵
for(int l=2; l<=n; l++)//长度为2-6的最小代价
{
for(int i=1; i<=n-l+1; i++)//遍历i的起始位置
{
int j=i+l-1;//j为l链的末位
m[i][j]=0x7fffffff;
for(int k=i; k<j; k++)
{
int q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}
cout<<m[1][n]<<endl;
}
void PrintAnswer(int s[N][N], int i, int j)
{
if(i==j)
cout<<"A"<<i;
else
{
cout<<"(";
PrintAnswer(s, i, s[i][j]);
PrintAnswer(s, s[i][j]+1, j);
cout<<")";
}
}
int main()
{
int m[N][N], s[N][N];
// int p[N]={30, 35, 15, 5, 10, 20, 25};
MatrixChain(m, s);
PrintAnswer(s, 1, N-1);
return 0;
}
代码借鉴:https://blog.csdn.net/qq_32919451/article/details/80643118