递归输出结果。
矩阵乘法每一格消耗O(n),结果行数等于左矩阵行数,列数等于右边列数。
res中存的分割点将[s,t]分为[s,k][k+1,t]是闭区间表示法
字符串与数字之间的转换看这篇文章
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<string>
#include<sstream>
using namespace std;
int dp[20][20];
int res[20][20];
int n;
int row[20];
int col[20];
const int INF=0x3f3f3f3f;
string resString(int s,int t)
{
if(s==t)
{
stringstream ss;
ss<<t;
string ts;
ss>>ts;
ts="A"+ts;
return ts;
}
int k=res[s][t];
string ts="";
if(k==s)
ts+=resString(s,k);
else
ts+="("+resString(s,k)+")";
ts+=" x ";
if(k+1==t)
ts+=resString(k+1,t);
else
ts+="("+resString(k+1,t)+")";
return ts;
}
int main()
{
int T=1;
while(scanf("%d",&n)&&n!=0)
{
for(int i=1;i<=n;i++)
scanf("%d%d",&row[i],&col[i]);
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{
if(i!=j)
dp[i][j]=INF;
else
dp[i][j]=0;
}
}
for(int l=2;l<=n;l++)
{
for(int i=l;i<=n;i++)
{
int s=i-l+1;
int t=i;
for(int j=i-l+1;j<i;j++)
{
int cost=dp[s][j]+dp[j+1][t]+row[s]*row[j+1]*col[t];
if(dp[s][t]>cost)
{
res[s][t]=j;
dp[s][t]=cost;
}
}
}
}
string resS="";
resS+="("+resString(1,n)+")";
const char* a=resS.c_str();
printf("Case %d: %s\n",T++,a);
}
}