1 #include "stdafx.h" 2 #include <iostream> 3 #include <math.h> 4 5 using namespace std; 6 7 #define N 7 8 #define INFINITY 100000000; 9 10 int m[N-1][N-1]; 11 int s[N-1][N-1]; 12 void Matrix_chain_order (int p[])//特别容易搞错边界,这种写法不好 13 { 14 for (int i = 0; i < N - 1; i++) 15 m[i][i] = 0; 16 for (int l = 2; l < N; l++) 17 for (int i = 0; i < N - l; i++) 18 { 19 int j = i + l - 1; 20 m[i][j] = INFINITY; 21 for (int k = i; k < j; k++) 22 { 23 int q = m[i][k] + m[k+1][j] + p[i]*p[k+1]*p[j+1]; 24 if (q < m[i][j]) 25 { 26 m[i][j] = q; 27 s[i][j] = k; 28 } 29 } 30 } 31 return; 32 } 33 34 void Print_optimal_parens (int i, int j)//打印输出最优 35 { 36 if(i==j) 37 cout<<"A["<<i<<"]"; 38 else 39 { cout<<"("; 40 Print_optimal_parens (i,s[i][j]); 41 Print_optimal_parens (s[i][j]+1,j); 42 cout<<")"; 43 } 44 } 45 int main() 46 { 47 int p[N] = {30, 35, 15, 5, 10, 20, 25}; 48 Matrix_chain_order (p); 49 Print_optimal_parens (0,5); 50 system("pause"); 51 return 0; 52 }