1 //3d1-1 重叠子问题的递归最优解 2 //A1 30*35 A2 35*15 A3 15*5 A4 5*10 A5 10*20 A6 20*25 3 //p[0-6]={30,35,15,5,10,20,25} 4 #include "stdafx.h" 5 #include <iostream> 6 using namespace std; 7 8 const int L = 7; 9 10 int RecurMatrixChain(int i,int j,int **s,int *p);//递归求最优解 11 void Traceback(int i,int j,int **s);//构造最优解 12 13 int main() 14 { 15 int p[L]={30,35,15,5,10,20,25}; 16 17 int **s = new int *[L]; 18 for(int i=0;i<L;i++) 19 { 20 s[i] = new int[L]; 21 } 22 23 cout<<"矩阵的最少计算次数为:"<<RecurMatrixChain(1,6,s,p)<<endl; 24 cout<<"矩阵最优计算次序为:"<<endl; 25 Traceback(1,6,s); 26 return 0; 27 } 28 29 int RecurMatrixChain(int i,int j,int **s,int *p) 30 { 31 if(i==j) return 0; 32 int u = RecurMatrixChain(i,i,s,p)+RecurMatrixChain(i+1,j,s,p)+p[i-1]*p[i]*p[j]; 33 s[i][j] = i; 34 35 for(int k=i+1; k<j; k++) 36 { 37 int t = RecurMatrixChain(i,k,s,p) + RecurMatrixChain(k+1,j,s,p) + p[i-1]*p[k]*p[j]; 38 if(t<u) 39 { 40 u=t; 41 s[i][j]=k; 42 } 43 } 44 return u; 45 } 46 47 void Traceback(int i,int j,int **s) 48 { 49 if(i==j) return; 50 Traceback(i,s[i][j],s); 51 Traceback(s[i][j]+1,j,s); 52 cout<<"Multiply A"<<i<<","<<s[i][j]; 53 cout<<" and A"<<(s[i][j]+1)<<","<<j<<endl; 54 }
二维数组**s 储存分割位置 s[i][j](i<j) 表示从第i个到第j个矩阵 将矩阵以其中第s[i][j]个分割
MatrixChain()函数递归实现动态规划 从最内层开始 每层动态选择相乘次数最少的 (外层的选择可能会改变内层的选择) 并将分割位置记录在**s数组中
1 int u = RecurMatrixChain(i,i,s,p)+RecurMatrixChain(i+1,j,s,p)+p[i-1]*p[i]*p[j]; 2 //为下面执行的找最小代价的算法提供比较初值 3 s[i][j] = i;//因为比较是<而不是<=,故也要对s[i][j]赋初值
转载于:https://www.cnblogs.com/yuelien/p/6353920.html