矩阵连乘(several matrix multiply)

Posted diamondDemand

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了矩阵连乘(several matrix multiply)相关的知识,希望对你有一定的参考价值。

#include <iostream>
#include <cstdio>

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<n; i++)
{
s[i] = new int[n];
}
for(int i=0; i<n; 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<j; k++)
{
int t = m[i][k] + m[k][j] + p[i-1] * p[k] * p[j];
if(t<m[i][j])
{
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;
}

以上是关于矩阵连乘(several matrix multiply)的主要内容,如果未能解决你的问题,请参考以下文章

杭电2018多校第四场(2018 Multi-University Training Contest 4) 1005.Problem E. Matrix from Arrays (HDU6336) -

动态规划之矩阵连乘

张量(Tensor)标量(scalar)向量(vector)矩阵(matrix)

算法设计——矩阵连乘问题

矩阵和向量的乘法顺序

矩阵乘法——连乘中的数学问题