# include <stdio.h>
# include <iomanip>
# include <iostream>
using namespace std;
const int L = 7 ;
void MatrixChain ( int n, int * * m, int * * s, int * p) ;
void PrintAnswer ( int * * s, int i, int j) ;
void outputArray ( int * * s) ;
int main ( )
{
int p[ L] ;
for ( int i = 0 ; i < L; i++ ) {
cout << "请输入第" << i + 1 << "个下标:" ;
cin >> p[ i] ;
}
int * * s = new int * [ L] ;
int * * m = new int * [ L] ;
for ( int i = 0 ; i < L; i++ )
{
s[ i] = new int [ L] ;
m[ i] = new int [ L] ;
}
MatrixChain ( 6 , m, s, p) ;
cout << "m矩阵的值为:" << endl;
outputArray ( m) ;
cout << endl;
cout << "s矩阵的值为:" << endl;
outputArray ( s) ;
cout << endl ;
cout << "矩阵运算划分:" << endl;
PrintAnswer ( s, 1 , 6 ) ;
cout << endl;
system ( "pause" ) ;
return 0 ;
}
void outputArray ( int * * s) {
for ( int i = 0 ; i < L; i++ ) {
for ( int j = 0 ; j < L; j++ ) {
if ( i >= j) {
s[ i] [ j] = 0 ;
}
if ( i == 0 )
{
cout << j << " " ;
}
else if ( j == 0 )
{
cout << j << " " ;
}
else
{
cout << s[ i] [ j] << " " ;
}
}
cout << endl;
}
}
void MatrixChain ( int n, int * * m, int * * s, int * p)
{
for ( int i = 1 ; i <= n; i++ )
{
m[ i] [ i] = 0 ;
}
for ( int r = 2 ; r <= n; r++ )
{
for ( int i = 1 ; i <= n - r + 1 ; i++ )
{
int j = i + r - 1 ;
m[ i] [ j] = m[ i + 1 ] [ j] + p[ i - 1 ] * p[ i] * p[ j] ;
s[ i] [ j] = i;
for ( int k = i + 1 ; k < j; k++ )
{
int t = m[ i] [ k] + m[ k + 1 ] [ j] + p[ i - 1 ] * p[ k] * p[ j] ;
if ( t < m[ i] [ j] )
{
m[ i] [ j] = t;
s[ i] [ j] = k;
}
}
}
}
}
void PrintAnswer ( int * * s, int i, int j)
{
if ( i == j)
{
cout << "A" << i;
}
else
{
cout << "(" ;
PrintAnswer ( s, i, s[ i] [ j] ) ;
PrintAnswer ( s, s[ i] [ j] + 1 , j) ;
cout << ")" ;
}
}