码迷,mamicode.com
首页 > 其他好文 > 详细

矩阵连乘(several matrix multiply)

时间:2017-09-27 21:50:26      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:ios   when   diff   矩阵连乘   i+1   use   size   problems   ==   

#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)

标签:ios   when   diff   矩阵连乘   i+1   use   size   problems   ==   

原文地址:http://www.cnblogs.com/1915884031A-qqcom/p/7603844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!