记录编号 43754 评测结果 AAAAA
题目名称 最优矩阵链乘 最终得分 100
用户昵称 GravatarTruth.Cirno 是否通过 通过
代码语言 C++ 运行时间 0.003 s
提交时间 2012-10-13 17:47:35 内存使用 0.36 MiB
显示代码纯文本
#include <iostream>
#include <cstdio>
using namespace std;

int a[110],f[110][110];

int minint(int a,int b)
{
	if(a<b)
		return(a);
	return(b);
}

int main(void)
{
	freopen("goodmatrix.in","r",stdin);
	freopen("goodmatrix.out","w",stdout);
	int i,j,k,n,l,r;
	cin>>n;
	for (i=1;i<=n+1;i++)
		cin>>a[i];
	n--;
	for (i=1;i<=n;i++)
		f[i][1]=a[i]*a[i+1]*a[i+2];
	for (i=1;i<n;i++)
	{
		f[i][2]=f[i+1][1]+a[i]*a[i+1]*a[i+3];//f[][] i+1 to i+1
		f[i][2]=minint(f[i][2],f[i][1]+a[i]*a[i+2]*a[i+3]);//f[][] i to i
	}
	for (j=3;j<=n;j++)
		for (i=1;i+j-1<=n;i++)
		{
			f[i][j]=f[i+1][j-1]+a[i]*a[i+1]*a[i+j+1];//f[][] i+1 to i+j-1
			f[i][j]=minint(f[i][j],f[i][j-1]+a[i]*a[i+j]*a[i+j+1]);//f[][] i to i+j-2
			l=i+1;
			r=i+j-2;
			for (k=l;k<=r;k++)
				f[i][j]=minint(f[i][j],f[i][k-i]+f[k+1][i+j-k-1]+a[i]*a[k+1]*a[i+j+1]);//f[][] i+1 to k-1 && k+1 to r
		}
	cout<<f[1][n]<<endl;
	return(0);
}