矩阵连乘(several matrix multiply)

#include
#include

using namespace std;


void traceBack(int i, int j, int **s)
{
if(i==j) //the function is used to record the optimal solution
{
return;
}
traceBack(i, s[i][j], s); //output the left solution
traceBack(s[i][j]+1, j, s); //output the right solution
cout << "A[" << i << ":" << s[i][j] << "] multiply [" << s[i][j] << ":" << j << "]" << endl; //A[1:1] multiply A[1:5]

}


void matrixChain(int p[], int n)
{
int m[n][n];
int **s = new int*[n];
for(int i=0; i {
s[i] = new int[n];
}
for(int i=0; i {
m[i][i] = 0;
s[i][i] = 0;
}
for(int r=2; r<=n; r++) //sub-problems of different sizes
{
for(int i=1; i<=n-r+1; i++) //the first matrix of each matrix-chain which size is r
{
int j = i + r - 1; //the last matrix of each matrix-chain which size is r
m[i][j] = m[i][i] + m[i+1][j] + p[i-1] * p[i] * p[j]; //multiplication times when the k=i
s[i][j] = i;
for(int k=i+1; k {
int t = m[i][k] + m[k][j] + p[i-1] * p[k] * p[j];
if(t {
m[i][j] = t; //record the smallest multiplication
s[i][j] = k; //record the location of split
}
}
}
}

traceBack(1, 5, s);
}


int main(void)
{
int s[] = {3, 2, 5, 10, 2, 3};
matrixChain(s, 6);
return 0;
}

转载于:https://www.cnblogs.com/1915884031A-qqcom/p/7603844.html

你可能感兴趣的:(矩阵连乘(several matrix multiply))