矩阵链乘法:
矩阵P={}
标准模板:
for(int i=2;i<=n;i++)
for(int j=1;j<=n-i+1;j++)
{
int temp = i+j-1;
dp[j][temp] = 1000000000;
for(int k=j;k<=temp-1;k++)
{
v = dp[j][k]+dp[k+1][temp]+p[j-1]*p[k]*p[temp];
if(v<dp[j][temp])
{
dp[j][temp] = v;
s[j][temp] = k;
}
}
}
相乘次数(答案) = dp[1][n]
打印最佳链乘表达式:
void print(int i,int j)
{
if(i==j)
cout<<"A"<<i;
else
{
cout<<"(";
print(i,s[i][j]);
//cout<<"*";是否带乘号*
print(s[i][j]+1,j);
cout<<")";
}
}
#include <iostream>
#include <cstring>
using namespace std;
#define X 11
int p[X];
int dp[X][X];
int s[X][X];
void print(int i,int j)
{
if(i==j)
cout<<"A"<<i;
else
{
cout<<"(";
print(i,s[i][j]);
cout<<" x ";
print(s[i][j]+1,j);
cout<<")";
}
}
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
int n;
int counter = 0;
int x,y,v;
while(cin>>n,n)
{
counter++;
for(int i=1;i<=n;i++)
{
cin>>x>>y;
p[i-1] = x;
}
p[n] = y;
for(int i=1;i<=n;i++)
dp[i][i] = 0;
for(int i=2;i<=n;i++)
for(int j=1;j<=n-i+1;j++)
{
int temp = i+j-1;
dp[j][temp] = 1000000000;
for(int k=j;k<=temp-1;k++)
{
v = dp[j][k]+dp[k+1][temp]+p[j-1]*p[k]*p[temp];
if(v<dp[j][temp])
{
dp[j][temp] = v;
s[j][temp] = k;
}
}
}
//cout<<dp[1][n]<<endl;
cout<<"Case "<<counter<<": ";
print(1,n);
cout<<endl;
}
return 0;
}