矩阵连乘问题


#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 << ")";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值