EOJ 1051:(算法作业4-1)完全加括号的矩阵连乘积(DP)

5 篇文章 0 订阅

题目链接:http://www.acm.cs.ecnu.edu.cn/problem.php?problemid=1051

题意:给你n的矩阵,要求求出一种加括号的方案使得做的乘法数量最少。

分析:
dp[i][j]表示从i到j的最优解, dp[i][j]=min(dp[i][k]+dp[k][j]+ ,记忆话搜索即可。

代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>

using namespace std;

const int maxn = 50 + 5;
const long long INF = (1LL << 63LL) - 1;

struct Matrix
{
    int x, y;
    long long num;
    friend Matrix operator * (const Matrix& a, const Matrix& b)
    {
        Matrix res;
        res.x = a.x;
        res.y = b.y;
        res.num = a.num + b.num + a.x * a.y * b.y;
        return res;
    }
};

int T, n, ans;
Matrix matrix[maxn], dp[maxn][maxn];

Matrix DP(int l, int r)
{
    if (dp[l][r].num >= 0)
        return dp[l][r];
    if (l + 1 == r)
    {
        dp[l][r].x = matrix[l].x;
        dp[l][r].y = matrix[l].y;
        dp[l][r].num = 0;
        return dp[l][r];
    }
    dp[l][r].num = INF;
    for (int i = l + 1; i < r; ++i)
    {
        Matrix a = DP(l, i);
        Matrix b = DP(i, r);
        Matrix c = a * b;
        if (c.num < dp[l][r].num)
            dp[l][r] = c;
    }
    return dp[l][r];
}

int main()
{
    scanf("%d", &T);
    for (int C = 0; C < T; ++C)
    {
        scanf("%d", &n);
        for (int i = 0; i <= n; ++i)
            for (int j = 0; j <= n; ++j)
                dp[i][j].num = -1;
        for (int i = 0; i < n; ++i)
            scanf("%d%d", &matrix[i].x, &matrix[i].y);
        printf("%lld\n", DP(0, n).num);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值