自我吐槽,连个注释都没有,哈哈哈哈哈哈哈!!!!
代码:
1 #include<iostream> 2 3 using namespace std; 4 5 typedef struct Matrix 6 { 7 int m; 8 int n; 9 }Matrix; 10 11 int Min(int a, int b) 12 { 13 return a < b ? a : b; 14 } 15 16 int MatrixChain(Matrix *MatArray, int i, int j) 17 { 18 if (i < j) 19 { 20 int MinResult = INT_MAX; 21 for (int t = 0; t + i < j; t++) 22 { 23 MinResult = Min(MinResult, MatrixChain(MatArray, i, i + t) + MatrixChain(MatArray, i + t + 1, j) + MatArray[i].m*MatArray[i+t].n*MatArray[j].n); 24 } 25 return MinResult; 26 } 27 else 28 return 0; 29 } 30 31 int dp[10][10]; 32 int s[10][10]; 33 34 int NonRecursionMatrixChain(Matrix *MatArray, int size) 35 { 36 for (int i = 0; i < size; i++) 37 { 38 dp[i][i] = 0; 39 } 40 for (int l = 2; l <= size; l++) 41 { 42 for (int i = 0; i < size - l + 1; i++) 43 { 44 int j = i + l -1; 45 int MinResult = INT_MAX; 46 int k; 47 for (int t = 0; i + t < j; t++) 48 { 49 int x = dp[i][i + t] + dp[i + t + 1][j] + MatArray[i].m*MatArray[i+t].n*MatArray[j].n; 50 if (x < MinResult) 51 { 52 k = i + t; 53 MinResult = x; 54 } 55 } 56 s[i][j] = k; 57 dp[i][j] = MinResult; 58 } 59 } 60 return dp[0][size-1]; 61 } 62 63 void ResultOut(int i, int j) 64 { 65 if (i == j) 66 { 67 cout <<"A"<<i; 68 } 69 else 70 { 71 cout << "("; 72 ResultOut(i, s[i][j]); 73 ResultOut(s[i][j] + 1, j); 74 cout << ")"; 75 } 76 } 77 78 void MatArrayInput(Matrix *MatArray, int size) 79 { 80 for (int i = 0; i < size; i++) 81 { 82 cin >> MatArray[i].m >> MatArray[i].n; 83 } 84 } 85 86 int main() 87 { 88 int size = 6; 89 Matrix *MatArray = (Matrix *)malloc(size * sizeof(Matrix)); 90 MatArrayInput(MatArray, size); 91 cout << NonRecursionMatrixChain(MatArray,6) << endl; 92 ResultOut(0, 5); 93 return 0; 94 }