#include <stdio.h>
#include <limits.h>
/*
矩阵连乘算法思想:
m[i][j]=0 i=j
m[i][j]=min(i<=k<j){m[i][k]+m[k+1][j]+Pi-1PkPj} i<j
*/
#define MAX_SIZE 10
void matrixChainOrder(int p[], int n, int m[MAX_SIZE][MAX_SIZE], int s[MAX_SIZE][MAX_SIZE]){
int i,j,k,r,t;
for(i=1;i<n;i++){
m[i][i]=0; //单位矩阵,也就是i=j的时候,为 0
}
for(r=2;r<=n;r++){//控制斜边
for(i=1;i<=n-r+1;i++){//n-r+1用于控制斜边上的数据的个数
j=i+r-1;
m[i][j]=m[i+1][j]+p[i-1]*p[i]*p[j];//此时k=i,在i处分开的话计算它的值作为初值
s[i][j]=i;
for(k=i+1;k<j;k++){//划分比较,得到最小值
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 printOptimalParentheses(int i, int j, int s[MAX_SIZE][MAX_SIZE]){//打印函数
if(i == j){
printf("A%d", i);
}
else{
printf("(");
printOptimalParentheses(i, s[i][j], s);
printOptimalParentheses(s[i][j] + 1, j, s);
printf(")");
}
}
int main(){
int n, i;
printf("Enter the number of matrices: ");//输入矩阵个数
scanf("%d", &n);
int p[n+1];
printf("Enter the dimensions of the matrices: ");//输入矩阵的维度
for(i = 0; i <= n; i++){
scanf("%d", &p[i]);
}
int m[MAX_SIZE][MAX_SIZE];
int s[MAX_SIZE][MAX_SIZE];
matrixChainOrder(p, n, m, s);
printf("Optimal Parenthesization: ");
printOptimalParentheses(1, n, s);
printf("\n");
return 0;
}
06-22
2万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-26
02-12
10-21
2278
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)