矩阵连乘问题的动态规划算法实现C语言
时间: 2023-10-27 17:07:24 浏览: 135
以下是矩阵连乘问题的动态规划算法实现的C语言代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
#define INF 0x7fffffff
int MatrixChainOrder(int p[], int n) {
int m[MAX_SIZE][MAX_SIZE], s[MAX_SIZE][MAX_SIZE];
int i, j, k, len, q;
for (i = 1; i <= n; i++) {
m[i][i] = 0;
}
for (len = 2; len <= n; len++) {
for (i = 1; i <= n - len + 1; i++) {
j = i + len - 1;
m[i][j] = INF;
for (k = i; k <= j - 1; k++) {
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
return m[1][n];
}
int main() {
int arr[] = {30, 35, 15, 5, 10, 20, 25};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Minimum number of multiplications is %d ", MatrixChainOrder(arr, n - 1));
return 0;
}
```
其中,`p[]`是矩阵的维度数组,`n`是矩阵个数。运行结果为:
```
Minimum number of multiplications is 15125
```
阅读全文