动态规划——矩阵链相乘
/** * @brief MatrixChainMultiplication Algorithm 15.2 * @author An * @data 2013.8.25 **/ #include <iostream> #include <limits> #define N 6 using namespace std; static int **m = new int*[N]; static int **s = new int*[N]; // static int *p = new int[N]; void MatrixChainOrder( int *p ) { for ( int i = 0; i != N; ++i ) { m[i] = new int[N]; s[i] = new int[N]; } for ( int i = 0; i != N; ++i ) { for ( int j = 0; j != N; ++j ) { m[i][j] = 0; s[i][j] = 0; } } for ( int i = 0; i != N; ++i ) { m[i][i] = 0; } for ( int l = 2; l <= N; ++l ) { for ( int i = 0; i != N - l + 1; ++i ) { int j = i + l - 1; m[i][j] = INT_MAX; for ( int k = i; k != j; ++k ) { int q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]; // p+1 if ( q < m[i][j] ) { m[i][j] = q; s[i][j] = k; } } } } } void PrintOptimalParens( int **ss, int i, int j ) { if ( i == j ) { cout << "A" << i + 1; } else { cout << "("; PrintOptimalParens( ss, i, s[i][j] ); PrintOptimalParens( ss, s[i][j] + 1, j ); cout << ")"; } } void PrintMatrix( int **Ma, int length ) { for ( int i = 0; i != length; ++i ) { for ( int j = 0; j != length; ++j ) { cout << Ma[i][j] << " "; } cout << endl; } cout << endl; } int main() { int *p = new int[N + 1]; int a[] = { 30, 35, 15, 5, 10, 20, 25 }; for ( int i = 0; i != N + 1; ++i ) { p[i] = a[i]; } MatrixChainOrder( p ); PrintOptimalParens( s, 0, N - 1); cout << endl; PrintMatrix( m, N ); PrintMatrix( s, N ); return 0; }