#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
const int L = 7;
void MatrixChain(int n, int** m, int** s, int* p);
void PrintAnswer(int** s, int i, int j);//构造最优解
void outputArray(int** s);
int main()
{
int p[L];
for (int i = 0; i < L; i++) {
cout << "请输入第" << i + 1 << "个下标:";
cin >> p[i];
}
int** s = new int* [L];
int** m = new int* [L];
for (int i = 0; i < L; i++)
{
s[i] = new int[L];
m[i] = new int[L];
}
MatrixChain(6, m, s, p);
cout << "m矩阵的值为:" << endl;
outputArray(m);
cout << endl;
cout << "s矩阵的值为:" << endl;
outputArray(s);
cout << endl ;
cout << "矩阵运算划分:" << endl;
PrintAnswer(s, 1, 6);
cout << endl;
system("pause");
return 0;
}
void outputArray(int** s) {
for (int i = 0; i < L; i++) {
for (int j = 0; j < L; j++) {
if (i >= j) {
s[i][j] = 0;
}
if (i == 0)
{
cout << j << " ";
}
else if (j == 0)
{
cout << j << " ";
}
else
{
cout << s[i][j] << " ";
}
}
cout << endl;
}
}
void MatrixChain(int n, int** m, int** s, int* p)
{
for (int i = 1; i <= n; i++)
{
m[i][i] = 0;
}
for (int r = 2; r <= n; r++) //r为当前计算的链长(子问题规模)
{
for (int i = 1; i <= n - r + 1; i++)//n-r+1为最后一个r链的前边界
{
int j = i + r - 1;//计算前边界为r,链长为r的链的后边
m[i][j] = m[i + 1][j] + p[i - 1] * p[i] * p[j];//将链ij划分为A(i) * ( A[i+1:j] )
s[i][j] = i;
for (int k = i + 1; k < j; k++)
{
//将链ij划分为( A[i:k] )* (A[k+1:j])
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;
}
}
}
}
}
void PrintAnswer(int** s, int i, int j)
{
if (i == j)
{
cout << "A" << i;
}
else
{
cout << "(";
PrintAnswer(s, i, s[i][j]);
PrintAnswer(s, s[i][j] + 1, j);
cout << ")";
}
}
矩阵连乘问题
于 2022-05-31 17:22:05 首次发布