一、 实验目的及任务
- 掌握动态规划算法的基本步骤:找出最优解的性质,并刻画其结构特征;递归地定义最优值;以自底向上的方式计算出最优值;根据计算最优值时得到的信息,构造最优解。
- 设计并实现矩阵连乘的算法,掌握动态规划算法。
二、 实验环境
c++
三、 问题描述
给定n个矩阵<A1,A2,…,An>,其中Ai与Ai+1是可乘的,i=1,2…,n。 矩阵 Ai 的维度为 P i-1´ Pi,如何确定计算矩阵连乘积的计算次序,使得依此次序计算矩阵连乘积需要的数乘次数最少。
四、 编程任务
设计一个动态规划算法确定计算矩阵连乘积的计算次序,使得依此次序计算矩阵连乘积需要的数乘次数最少。
五、 数据输入
随机产生10以上的字符,放入输入文件input.txt,如:P={30,35,15,5,10,20,25}
六、 结果输出
程序运行结束时,将矩阵连乘的加括号方式以及所计算的乘法次数输出。
实验结果
生成随机数,将随机数放入input
#include <iostream>
#include <fstream>
#include <random>
using namespace std;
int main() {
ofstream outfile("input.txt");
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(10, 100);
int n = 7; // 矩阵数
outfile << "P={";
for (int i = 0; i <= n; i++) {
outfile << dis(gen);
if (i < n) {
outfile << ",";
}
}
outfile << "}\n";
outfile.close();
return 0;
}
动态规划算法,从input中读取数据
#include <iostream>
#include <fstream>
#include <vector>
#include <climits>
using namespace std;
// 定义矩阵类
class Matrix {
public:
int rows;
int cols;
Matrix(int r = 0, int c = 0) : rows(r), cols(c) {}
int getRows() const { return rows; }
int getCols() const { return cols; }
void setRows(int r) { rows = r; }
void setCols(int c) { cols = c; }
};
// 动态规划求解矩阵连乘问题
void matrixChainOrder(vector<Matrix>& matrices, vector<vector<int>>& m, vector<vector<int>>& s) {
int n = matrices.size(); // 矩阵数量
for (int i = 1; i <= n; i++) { // 计算长度为 len 的矩阵链的最小代价
m[i][i] = 0; // 链长为1时,m[i][i] = 0
}
for (int len = 2; len <= n; len++) { // 枚举子问题规模
for (int i = 1; i <= n - len + 1; i++) { // 枚举子问题起点
int j = i + len - 1; // 子问题终点
m[i][j] = INT_MAX; // 初始化为无穷大
for (int k = i; k < j; k++) { // 枚举断点
int q = m[i][k] + m[k+1][j] + matrices[i-1].getRows() * matrices[k].getCols() * matrices[j-1].getCols(); // 计算代价
if (q < m[i][j]) { // 如果代价更小,则更新最优解
m[i][j] = q;
s[i][j] = k; // 记录最优断点位置
}
}
}
}
}
// 输出加括号的矩阵连乘方式
void printOptimalParens(vector<vector<int>>& s, vector<Matrix>& matrices, int i, int j) {
if (i == j) {
cout << "A" << i;
} else {
cout << "(";
printOptimalParens(s, matrices, i, s[i][j]);
printOptimalParens(s, matrices, s[i][j] + 1, j);
cout << ")";
}
cout << "[" << matrices[i-1].getRows() << "x" << matrices[j-1].getCols() << "]";
}
int main() {
// 从文件读取矩阵规模
vector<int> P;
ifstream infile("input.txt");
char ch;
while (infile >> ch) {
if (ch >= '0' && ch <= '9') {
infile.putback(ch);
int x;
infile >> x;
P.push_back(x);
}
}
infile.close();
int n = P.size() - 1; // 矩阵数
// 构造矩阵
vector<Matrix> matrices;
for (int i = 0; i < n; i++) {
matrices.push_back(Matrix(P[i], P[i+1]));
}
// 初始化代价矩阵和断点矩阵
vector<vector<int>>* m = new vector<vector<int>>(n+1, vector<int>(n+1));
vector<vector<int>>* s = new vector<vector<int>>(n+1, vector<int>(n+1));
// 求解矩阵连乘问题
matrixChainOrder(matrices, *m, *s);
// 输出结果
cout << "最小代价为:" << (*m)[1][n] << endl;
cout << "矩阵连乘方式为:";
printOptimalParens(*s, matrices, 1, n);
cout << endl;
// 释放内存
delete m;
delete s;
return 0;
}