代码:
#include <iostream>
using namespace std;
const int N = 6;
const int MaxNum = 0x3f3f3f3f;
int p[N + 1] = {30,35,15,5,10,20,25};
int m[N + 1][N + 1] = {0};
int s[N + 1][N + 1] = {0};
int MatrixChainOrder()
{
//初始化-处理区间中元素为1的区间
for (int i = 1;i <= N;i++)
{
m[i][i] = 0;
}
//递推
for (int len = 2;len <= N;len++)//区间长度
{
for (int i = 1;i <= N - len + 1;i++)//每种区间的起点
{
int j = i + len - 1; //每种区间的终点
m[i][j] = MaxNum;
for (int k = i;k < j;k++)
{
int cost = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (m[i][j] > cost)
{
m[i][j] = cost;
s[i][j] = k;
}
}
}
}
return m[1][N];
}
//x和y表示区间的起点和终点
void PrintOptimalParens(int x,int y)
{
if (x == y) //区间起点 = 终点时,表示区间中只有一个元素
{
cout<<"A"<<x;
return;
}
else
{
cout<<"(";
PrintOptimalParens(x,s[x][y]);
PrintOptimalParens(s[x][y] + 1,y);
cout<<")";
}
}
int main()
{
cout<<MatrixChainOrder()<<endl;
PrintOptimalParens(1,N);
system("pause");
return 1;
}