动态规划之矩阵连乘问题c语言
时间: 2023-11-17 09:56:55 浏览: 254
矩阵连乘问题是一个经典的动态规划问题,其目标是找到一种最优的矩阵相乘顺序,使得计算矩阵乘积所需的标量乘法次数最少。下面是一个 C 语言实现的矩阵连乘问题的代码:
```c
#include <stdio.h>
#include <limits.h>
#define MAX_SIZE 100
int matrixChainOrder(int p[], int n) {
int m[MAX_SIZE][MAX_SIZE];
int i, j, k, L, q;
for (i = 1; i <= n; i++) {
m[i][i] = 0;
}
for (L = 2; L <= n; L++) {
for (i = 1; i <= n - L + 1; i++) {
j = i + L - 1;
m[i][j] = INT_MAX;
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;
}
}
}
}
return m[1][n];
}
int main() {
int p[] = {30, 35, 15, 5, 10, 20, 25};
int n = sizeof(p) / sizeof(p[0]) - 1;
printf("Minimum number of multiplications is %d\n", matrixChainOrder(p, n));
return 0;
}
```
阅读全文