#include
#define max 100
void matrixChain(int *p,int n,int m[max][max],int s[max][max]){ //矩阵连乘的函数算出最小的次数
int i,r,j,k,t;
for(i=1;i<=n;i++){ //初始化m[i][j],一个矩阵的相乘所用的次数为0
for(j=1;j<=n;j++){
m[i][j]=0;
}
}
for(r=2;r<=n;r++){ //r表示几个矩阵相乘
for(i=1;i<=n-r+1;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 t=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]; //找出最小的矩阵矩阵相乘次数的分隔点
if(t m[i][j]=t;
s[i][j]=k;
}
}
}
}
}
int main(void){
int p[max+1];
int num;
int m[max][max];
int s[max][max];
int i,j,col,row;
printf("Please Input the number of martrix:");
scanf("%d",&num);
for(i=1;i<=num;i++){
if(i==1){
printf("Please input the martrix %d rows:",i);
scanf("%d",&row);
printf("Please input the martrix %d cols:",i);
scanf("%d",&col);
p[i-1]=row;
p[i]=col;
}
else{
printf("Please Input the %d martrix cols:",i);
scanf("%d",&col);
p[i]=col;
}
}
matrixChain(p,num,m,s);
for(i=1;i<=num;i++){
for(j=1;j<=num;j++){
printf("%d\t",m[i][j]);
}
printf("\n");
}
return 0;
}
阅读(1241) | 评论(0) | 转发(0) |