问题描述:给定一组可以连乘的矩阵,求最佳相乘顺序,使得总的计算次数最少。
动态规划算法:
#include <stdio.h>
void traceback(int i, int j, int **s)
{
if (i==j) return;
traceback(i,s[i][j], s);
traceback(s[i][j]+1,j,s);
printf("A[%d][%d] and A[%d][%d]\n",i,s[i][j],s[i][j]+1,j);
}
int main()
{
int n,i,j,k,r;
int *p;
int **m, **s;
printf("please input the number of matrix:");
scanf("%d",&n);
p=new int[n+1];
m=new int *[n+1];
s=new int *[n+1];
for(i=0;i<n+1;i++)
{
m[i]=new int[n+1];
s[i]=new int[n+1];
}
printf("input the dimensions of all matrix:");
for(i=0;i<n+1;i++)
scanf("%d", p+i);
for(i=1;i<n+1;i++)
m[i][i]=0;
for(r=2;r<=n;r++)
{
for(i=1;i<=n+1-r;i++)//运算的开始位置
{
j=i+r-1;
m[i][j]=m[i+1][j]+p[i-1]*p[i]*p[j];
s[i][j]=i;
for(k=i+1;k<j;k++){
int temp=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(temp<m[i][j]){
m[i][j]=temp;
s[i][j]=k;
}
}
}
}
//printf("\n%d\n",m[1][n]);
traceback(1,n,s);
return 0;
}
递归算法:
#include <stdio.h>
int **s,*p;
int recurMatrix(int i, int j)
{
int u,k;
if (i==j)
u=0;
else
{
u=recurMatrix(i,i)+recurMatrix(i+1,j)+p[i-1]*p[i]*p[j];
s[i][j]=i;
for(k=i+1;k<j;k++)
{
int temp=recurMatrix(i,k)+recurMatrix(k+1,j)+p[i-1]*p[k]*p[j];
if(temp<u)
{
s[i][j]=k;
u=temp;
}
}
}
return u;
}
void traceback(int i, int j, int **s)
{
if (i==j) return;
traceback(i,s[i][j], s);
traceback(s[i][j]+1,j,s);
printf("A[%d][%d] and A[%d][%d]\n",i,s[i][j],s[i][j]+1,j);
}
int main()
{
int n,i,j,k,r;
int **m;
printf("please input the number of matrix:");
scanf("%d",&n);
p=new int[n+1];
m=new int *[n+1];
s=new int *[n+1];
for(i=0;i<n+1;i++)
{
m[i]=new int[n+1];
s[i]=new int[n+1];
}
printf("input the dimensions of all matrix:");
for(i=0;i<n+1;i++)
scanf("%d", p+i);
printf("the total number is %d.\n",recurMatrix(1,n));
traceback(1,n,s);
return 0;
}
备忘录算法:
#include <stdio.h>
int **s,*p, **m;
int lookup(int i, int j)
{
int u,k, temp;
if(m[i][j]>0)
return m[i][j];
if(i==j)
u=0;
else{
u=lookup(i,i)+lookup(i+1,j)+p[i-1]*p[i]*p[j];
s[i][j]=i;
for(k=i+1;k<j;k++){
temp=lookup(i,k)+lookup(k+1,j)+p[i-1]*p[k]*p[j];
if(temp<u)
{
u=temp;
s[i][j]=k;
}
}
}
return u;
}
void traceback(int i, int j, int **s)
{
if (i==j) return;
traceback(i,s[i][j], s);
traceback(s[i][j]+1,j,s);
printf("A[%d][%d] and A[%d][%d]\n",i,s[i][j],s[i][j]+1,j);
}
int main()
{
int n,i,j;
printf("please input the number of matrix:");
scanf("%d",&n);
p=new int[n+1];
m=new int *[n+1];
s=new int *[n+1];
for(i=0;i<n+1;i++)
{
m[i]=new int[n+1];
s[i]=new int[n+1];
}
//初始化
for(i=1;i<n+1;i++)
for(j=1;j<n+1;j++)
m[i][j]=0;
printf("input the dimensions of all matrix:");
for(i=0;i<n+1;i++)
scanf("%d", p+i);
printf("the total number is %d.\n",lookup(1,n));
traceback(1,n,s);
return 0;
}