下面是矩阵连乘问题的算法实现
#include<iostream.h>
void MatrixChain(int p[],int n,int m[6][6],int s[6][6]);
void Traceback(int i,int j,int s[6][6]);
int main()
{
int p[]={30,35,15,5,10,20,25};
int n=6;
int m[6][6];
int s[6][6];
MatrixChain(p,n,m,s);
int i=1,j=6;
Traceback(i,j,s);
return 0;
}
void MatrixChain(int p[],int n,int m[6][6],int s[6][6])
{
for(int i=0;i<n;i++)m[i][i]=0;
for(int r=1;r<n;r++)
for(int i=0;i<n-r+1;i++)
{
int j=i+r-1;
m[i][j]=m[i+1][j]+p[i-1]*p[i]*p[j];
s[i][j]=i;
for(int k=i+1;k<j;k++)
{
int t=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(t<m[i][j])
{
m[i][j]=t;
s[i][j]=k;
}
}
}
}
void Traceback(int i,int j,int s[6][6])
{
if(i==j)cout<<"no-op"<<endl;
Traceback(i,s[i][j],s);
Traceback(s[i][i]+1,j,s);
cout<<"Multiply A"<<i<<","<<s[i][j];
cout<<"and A"<<(s[i][j]+1)<<","<<j<<endl;
}