动态规划-矩阵连乘(Matrix Chain-Product)

一.问题描述

在这里插入图片描述

We wish to compute the product

A = A_{1} \cdot A_{2}\cdot A_{3} \cdot \cdot \cdot A_{n-1} \cdot A_{n} ·

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 O\left ( n^3 \right )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值