1.最优子结构性质
证明:A[i][j]的最优解是以k划分的A[i][k],A[k+1][j],则A[i][k]是矩阵i到j的最优解
解:
假设其不是矩阵i到j的最优解,则存在一个解A'[i][k]的计算量更小;
所以存在一个A'[i][j]=A'[i][k]+A[k+1][j]+p[i-1]*p[k]*p[j],其计算量小于A[i][j],
与A[i][j]是最优解相矛盾。
2.递推方程
3.最优值
#include <iostream>
using namespace std;
void MatrixChain(int *p,int n,int m[7][7],int s[7][7])
{
for (int i = 1; i <= n; i++) m[i][i] = 0;
for (int r = 2; r <= n; r++)
for (int i = 1; i <= n - 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; 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;}
}
}
}
int main(int argc, char** argv) {
int n=6;
int p[7]={30,35,15,5,10,20,25};
int m[7][7];
int s[7][7];
for(int i=0;i<=n;i++){
for(int j=0;j<=n;j++){
m[i][j]=0;
s[i][j]=0;
}
}
MatrixChain(p,n,m,s);
cout<<"m: "<<endl;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){cout<<m[i][j]<<"\t";}
cout<<endl;}
cout<<endl<<endl;
cout<<"s: "<<endl;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){cout<<s[i][j]<<"\t";}
cout<<endl;
}
return 0;
}
m[i][j]
1 | 2 | 3 | 4 | 5 | 6 | |
1 | 0 | 15750 | 7875 | 9375 | 11875 | 15125 |
2 | 0 | 2625 | 4375 | 7125 | 10500 | |
3 | 0 | 750 | 2500 | 5375 | ||
4 | 0 | 1000 | 3500 | |||
5 | 0 | 5000 | ||||
6 | 0 |
s[i][j]
1 | 2 | 3 | 4 | 5 | 6 | |
1 | 0 | 1 | 1 | 3 | 3 | 3 |
2 | 0 | 2 | 3 | 3 | 3 | |
3 | 0 | 3 | 3 | 3 | ||
4 | 0 | 4 | 5 | |||
5 | 0 | 5 | ||||
6 | 0 |
4.最优解
由s数组可知,
A[1][6]由3划分,即A[1]3]和A[4][6];
而A[1][3]由1划分,即A[1][1],A[2][3];
A[4][6]由5划分,即A[4][5],A[6][6]