UVA 348 DP 矩阵乘法 输出结果

35 篇文章 0 订阅

递归输出结果。

矩阵乘法每一格消耗O(n),结果行数等于左矩阵行数,列数等于右边列数。

res中存的分割点将[s,t]分为[s,k][k+1,t]是闭区间表示法

字符串与数字之间的转换看这篇文章

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<string>
#include<sstream>
using namespace std;

int dp[20][20];
int res[20][20];
int n;
int row[20];
int col[20];

const int INF=0x3f3f3f3f;


string resString(int s,int t)
{
	if(s==t)
	{
		stringstream ss;
		ss<<t;
		string ts;
		ss>>ts;
		ts="A"+ts;
		return ts;
	}
	int k=res[s][t];
	string ts="";
	if(k==s)
		ts+=resString(s,k);
	else
		ts+="("+resString(s,k)+")";
	ts+=" x ";
	if(k+1==t)
		ts+=resString(k+1,t);
	else
		ts+="("+resString(k+1,t)+")";
	return ts;
}
int main()
{
	int T=1;
	while(scanf("%d",&n)&&n!=0)
	{
		for(int i=1;i<=n;i++)
			scanf("%d%d",&row[i],&col[i]);
		for(int i=0;i<20;i++)
		{
			for(int j=0;j<20;j++)
			{
				if(i!=j)
					dp[i][j]=INF;
				else
					dp[i][j]=0;
			}
		}
		for(int l=2;l<=n;l++)
		{
			for(int i=l;i<=n;i++)
			{
				int s=i-l+1;
				int t=i;
				for(int j=i-l+1;j<i;j++)
				{
					int cost=dp[s][j]+dp[j+1][t]+row[s]*row[j+1]*col[t];
					if(dp[s][t]>cost)
					{
						res[s][t]=j;
						dp[s][t]=cost;
					}
				}
			}	
		}
		string resS="";
		resS+="("+resString(1,n)+")";
		const char* a=resS.c_str(); 
		printf("Case %d: %s\n",T++,a);	
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值