View Code
#include <stdio.h> #include <string.h> #define SIZE 6 typedef struct MATRIX { int row; int col; }matrix; int m[SIZE][SIZE] = {0}; int s[SIZE][SIZE] = {0}; void matrixChainOrder(matrix *p) { int i, j, l, k; int n = 6;//sizeof(p)/sizeof(matrix); for (i = 0; i < n; i++) { m[i][i] = 0; } for (l = 2; l <= n ; l++) { for (i = 0; i < n-l+1; i++) { j = i + l - 1; m[i][j] = 0x7fffffff;//开始设置为0xffffffff为-1 for (k = i; k <= j; k++) { int q = m[i][k] + m[k+1][j] + (p[i].row) * (p[k].col) * (p[j].col); if (q < m[i][j]) { m[i][j] = q; s[i][j] = k+1; } } } } } void printOptimalParent(int (*s)[6], int i, int j) { if (i == j) { printf("A%d", i); } else { printf("("); printOptimalParent(s, i, s[i-1][j-1]); printOptimalParent(s, s[i-1][j-1]+1, j); printf(")"); } } int main() { matrix matrix[6] = {{30,35}, {35, 15}, {15, 5}, {5, 10}, {10, 20}, {20, 25}}; matrixChainOrder(matrix); printOptimalParent(s, 1, 6); printf("\n"); return 0; }