一.问题描述
We wish to compute the product
·
where Ai is a di−1 × di matrix. Because matrix multiplication is associative we can clever parenthesise the product to minimise the number of scalar multiplications
二.例子
Let n = 3, d0 = 5, d1 = 50, d2 = 20 and d3 = 10. (A1·A2)·A3. We first compute the 5×20 matrix A0 = A1·A2. This requires 5·50·20 = 5000 scalar multiplications. Next we compute the 5 × 10 matrix A = A0 · A3. This requires 5 · 20 · 10 = 1000 scalar multiplications, 6000 in total.
A1 ·(A2 ·A3). This time we start computing the 50×10 matrix A00 = A2 ·A3. This requires 50 · 20 · 10 = 10000 scalar multiplications. Now we obtain the 5 × 10 matrix A as A1 · A00 . This requires 5 · 50 · 10 = 2500 scalar multiplications, 12500 in total.
三.问题分析
四.建立递归关系(Recurrence Equation)
If the minimum in the expression for N[i, k] is realised for j then the last matrix multiplication in the product Ai · · · Ak should be (Ai · · · Aj ) · (Aj+1 · · · Ak).
五.Pseudo Code
六.代码实现
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
#define MAX 0xfffffff
#define N 100
int n;
int p[N];
int s[N][N],dp[N][N]; //S存储切割位置,dp存储最优值
void MatricChain(){
for(int i=0;i<n+1;i++)//赋初值
for(int j=0;j<n+1;j++){
dp[i][j]=MAX;
s[i][j]=0;
}
for(int i=0;i<=n;i++){
cin>>p[i];
dp[i][i]=0;//只有一个矩阵时不能相乘
}
for(int L=2;L<=n;L++){//相乘矩阵的个数
for(int i=1;i<=n;i++){
int j=i+L-1;
if(j>n) break;
for(int k=i;k<j;k++){//遍历切割位置
int min_=dp[i][j];
int temp=dp[i][k]+dp[k+1][j]+p[i-1]*p[k]*p[j];
if(temp<min_){
dp[i][j]=temp;
min_=temp;
s[i][j]=k;
}
// dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+p[i-1]*p[k]*p[j]);
}
}
}
}
void Traceback(int i,int j){
if(i==j) return;
int k=s[i][j];
Traceback(i,k);
Traceback(k+1,j);
cout<<"A["<<i<<":"<<k<<"]*A["<<k+1<<":"<<j<<"]"<<endl;
}
int main()
{
cin>>n;
MatricChain();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
cout<<setw(10)<<dp[i][j]<<" ";
cout<<endl;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
cout<<setw(5)<<s[i][j]<<" ";
cout<<endl;
}
cout<<"连乘的最少次数是"<<dp[1][n]<<"次。"<<endl;
Traceback(1,n);
}
/*
6
2 7 5 4 2 3 8
5
30 35 15 5 10 20
*/
七.时间复杂度(Running Time)
The correctness is obvious. We compute the values N[i, i] in time O(n). The three nested for-loops contribute a factor n each. The arithmetic operations and assignments require constant time. Therefore the algorithm runs in