前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >矩阵链乘——动态规划初探讨

矩阵链乘——动态规划初探讨

作者头像
天道Vax的时间宝藏
发布2021-08-11 10:46:30
3700
发布2021-08-11 10:46:30
举报
文章被收录于专栏:用户5305560的专栏

给定n个矩阵链<A1,A2,...,An>,矩阵Ai的规模为pi-1*pi(1≤i≤n),求完全括号化方案,使得A1A2,...An所需标量乘法次数最小。

代码语言:javascript
复制
#include<iostream>
#include<map>
#include<string>
#include<stack>
using namespace std;

struct matrix {
    int row;
    int column;
};

int main() {
    int n; string ch;
    string str;
    int li, co;
    map<string, matrix>m;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> ch >> li >> co;
        m[ch].row = li;
        m[ch].column = co;
    }
    while ((cin >> str)){    
        stack<string>s;
        string a, b;
        int sum = 0;
        bool flag = true;
        for (int i = 0; i < str.length(); i++) {
            if (str[i] == '(') continue;
            else if (str[i] == ')') {
                a = s.top(); s.pop();
                b = s.top(); s.pop();
                if (m[b].column == m[a].row) {
                    sum += m[b].row*m[b].column*m[a].column;
                    string ba;
                    ba = b + a;
                    s.push(ba);
                    m[ba].row = m[b].row;
                    m[ba].column = m[a].column;
                }
                else {
                    flag = false;
                    break;
                }
            }
            else {
                string s2;
                s2 = str[i];
                s.push(s2);
            }
        }
        if(flag) cout << sum << endl;
        else cout << "error" << endl;
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档