求矩阵连乘的最优加括号方式c++代码
时间: 2024-05-26 13:10:06 浏览: 100
以下是矩阵连乘的最优加括号方式的 C 代码:
#include<stdio.h>
#include<limits.h>
int MatrixChainOrder(int p[], int n) {
int m[n][n];
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 - 1];
}
int main() {
int arr[] = { 10, 20, 30, 40, 30 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Minimum number of multiplications: %d \n",
MatrixChainOrder(arr, n));
return 0;
}
如果您有任何关于该代码的问题,欢迎随时向我提问!
阅读全文