矩阵连乘-区间DP

42 篇文章 1 订阅
9 篇文章 0 订阅

山再高,往上爬,总能登顶;
路再长,走下去,定能到达。

矩阵连乘-区间DP

题目描述

一个A×B的矩阵乘以一个B×C的矩阵将得到一个A×C的矩阵,时间复杂度为A×B×C。矩阵乘法满足结合律(但不满足交换律)。顺序给出n个矩阵的大小,请问计算出它们的乘积的最少需要花费多少时间。

输入

第一行输入一个正整数n(n≤100),表示有n个矩阵。
接下来m行每行两个正整数Xi,Yi,其中第i行的两个数表示第i个矩阵的规模为Xi × Yi。所有的Xi、Yi<=100。输入数据保证这些矩阵可以相乘。

输出

输出最少需要花费的时间。

Sample Input

3
10 100
100 5
5 50

Sample Output

7500

Hint

顺序计算总耗时7500;先算后两个总耗时75000。

考察思想
区间dp

思路分析
在这里插入图片描述
这张图演示的是dp的动态过程
意思是选择1-n之间的任意区间,在这个区间内寻找合并的最优解。当我们选择出最优解后,就可以为下一次的调用提供最优解,这样就实现的了dp。
PS
浅蓝色代表选择的区间,深蓝色代表该区间内的划分
dp的思想就是看看当前的区间可以由哪两个区间得出,让这两个区间结合,求这个代价的最小值。
AC时间到

#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<utility>
#include<stdio.h>
#include<vector>
#include <stack>
#include<string>
#include<math.h>
#include<cmath>
#include<queue>
#include<map>
#pragma warning(disable:4244)
#define PI 3.1415926536
#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll ll_inf = 9223372036854775807;
const int int_inf = 2147483647;
const short short_inf = 32767;
const char char_inf = 127;
inline ll read() {
	ll c = getchar(), Nig = 1, x = 0;
	while (!isdigit(c) && c != '-')c = getchar();
	if (c == '-')Nig = -1, c = getchar();
	while (isdigit(c))x = ((x << 1) + (x << 3)) + (c ^ '0'), c = getchar();
	return Nig * x;
}
inline void out(ll a)
{
	if (a < 0)putchar('-'), a = -a;
	if (a >= 10)out(a / 10);
	putchar(a % 10 + '0');
}
ll qpow(ll x, ll n, ll mod) {
	ll res = 1;
	while (n > 0) {
		if (n & 1)res = (res * x) % mod;
		x = (x * x) % mod; n >>= 1;
	}
	return res;
}
#define read read()
ll dp[1000][1000];
struct node {
	int a, b;
}save[100000];//用结构体表示矩阵
int main()
{
	ll n = read;
	for (ll i = 1; i <= n; i++)//从1开始从0开始都一样,只是在细节上有些处理不同
	{
		save[i].a = read;
		save[i].b = read;
	}//此处已说过相邻的两个是可以相乘的,所以不用在意顺序了。
	for (int i = 1; i < n; i++)//代表区间宽度,
	{                          //当i为1时,表示他和相邻1个为一组进行运算,同理
		for (int j = 1, k = j + i; k <= n; k++, j++)
		{                      //代表选择的区间,j为起点,k为终点,两者同时平移
			ll minn = int_inf; //找到这一段区间应当如何分割才可以达到最优解
			for (int l = j + 1; l <= k; l++)
			{        //选择已经链接好的两个区间,加上缝合这两个区间的代价就是temp
				ll temp = dp[j][l - 1] + dp[l][k] + save[j].a * save[l].a * save[k].b;
				minn = min(temp, minn);
			}
			dp[j][k] = minn;//可以得出当前dp的最优解
		}
	}
	cout << dp[1][n] << endl;//输出从1-n的最优解
	return 0;
}

By-轮月

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Round moon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值