矩阵连乘

这个地方要注意动态数组的初始化:

下面是代码,有两种动态数组的初始化方式

#include<iostream>
#include<cstdlib>
using namespace std;
void MatrixChain(int *p,int n,int * *m,int * *s)
{
	for(int i = 1;i <= n;i++)
	m[i][i] = 0;
	for(int r = 2;r <= n;r++)
	for(int i = 1;i <= n - r + 1;i++)
	{
		int j = i + r - 1;
		m[i][j] = m[i + 1][j] +p[i - 1] * p[i] *p[j];
		s[i][j] = i;
		for(int k = i + 1;k < j;k++)
		{
			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;
			}
		}
	}
	cout <<"最少数乘次数为:" << m[1][n] << endl;
}
void Traceback(int i,int j,int **s)
{
	if(i == j)
	return ;
	Traceback(i,s[i][j],s);
	Traceback(s[i][j] + 1,j,s);
	cout << "Multiply A" << i << "," << s[i][j];
	cout << "and A" << (s[i][j] + 1) << "," << j << endl;
}
int main()
{
	int n;
	cin >> n;
	int list[n + 1];
    /*int** m = new int*[n+1];//动态数组的初始化方式1
    m[0] = new int[(n+1)*(n+1)];
    int** s = new int*[n+1];
    s[0] = new int[(n+1)*(n+1)];
    for(int i = 1; i < n+1; i ++)
    {
        m[i] = m[i-1] + n+1;
        s[i] = s[i-1] + n+1;
    }*/
    int **s = new int *[n + 1];//动态数组的初始化方式二
    int **m = new int *[n + 1];
    for(int i=0;i< n + 1;i++)
    {
        s[i] = new int[n + 1];
        m[i] = new int[n + 1];
    }
	for(int i = 0;i < n + 1;i++)
	cin >> list[i];
	if(n == 1)
	cout << "计算次数为:0" << endl;
	else
	MatrixChain(list,n,m,s);
	Traceback(1,n,s);
	return 0;
}
/*
6
30 35 15 5 10 20 25
*/

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页