矩阵连乘动态规划C语言代码
时间: 2023-08-27 10:05:20 浏览: 62
以下是矩阵连乘动态规划的 C 语言代码示例:
```c
#include <stdio.h>
#define MAX_SIZE 50
void matrixChainOrder(int p[], int n, int m[MAX_SIZE][MAX_SIZE], int 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] = 99999999;
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;
}
}
}
}
}
void printOptimalParens(int s[MAX_SIZE][MAX_SIZE], int i, int j) {
if (i == j) {
printf("A%d", i);
} else {
printf("(");
printOptimalParens(s, i, s[i][j]);
printOptimalParens(s, s[i][j] + 1, j);
printf(")");
}
}
int main() {
int n, p[MAX_SIZE], m[MAX_SIZE][MAX_SIZE], s[MAX_SIZE][MAX_SIZE];
printf("Enter number of matrices: ");
scanf("%d", &n);
printf("Enter dimensions of matrices:\n");
for (int i = 0; i <= n; i++) {
scanf("%d", &p[i]);
}
matrixChainOrder(p, n, m, s);
printf("Optimal Parenthesization: ");
printOptimalParens(s, 1, n);
printf("\nMinimum number of multiplications: %d\n", m[1][n]);
return 0;
}
```
希望这个例子能帮到您!
阅读全文