矩阵乘法:设A1,A2.....An为矩阵序列,Ai为Pi-1*Pi阶矩阵,确定乘法顺序使得元素相乘的总次数最少。
#include <iostream>
using namespace std;
void MatrixChain(int P[],int size, int m[][7],int s[][7]);
void CheckTable(int s[][7],int i,int j);
int main()
{
int P[7] = {30,35,15,5,10,20,25};
int m[7][7];
int s[7][7];
for ( int i = 0;i < 7;i++)
{
for( int j = 0;j < 7;j++ )
{
m[i][j] = 0;
s[i][j] = 0;
}
}
MatrixChain(P,7,m,s);
CheckTable(s,1,6);
}
void MatrixChain(int P[],int size,int m[][7],int s[][7])
{
int i = 0;
int j = 0;
//清零//////////
for ( i = 0;i < size;i++)
{
for( j = 0;j < size;j++ )
{
m[i][j] = 0;
s[i][j] = 0;
}
}
for (int r = 2;r <= size;r++)
{
for (i = 1;i < size-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-1; 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;
cout <<r<<" "<<t<<" "<<k<<endl;
}
}
}
}
}
void CheckTable(int s[][7],int i,int j)
{
if((j-i) <= 1 )
return;
int k = s[i][j];
cout<<k<<endl;
CheckTable(s,i,k);
CheckTable(s,k+1,j);
}