Matrix Chain Multiplication UVA - 442栈的表达式分割模拟

本文探讨了使用栈和map数据结构处理矩阵运算表达式的方法,通过实例讲解如何验证矩阵乘法的合法性并计算矩阵乘法的成本。代码实现基于C++,展示了如何将矩阵的行和列存储在map中,并利用栈进行表达式的分割与计算。

https://cn.vjudge.net/problem/UVA-442
分析:考察栈对简单表达式的分割。先将每个矩阵的行和列存入一个map中,键为矩阵名称,值为一个pair里面为矩阵的行和列。我们先把表达式中‘)’前的字母压入栈中,然后从栈顶pop出两个矩阵,计算乘积和,然后将矩阵乘为一个矩阵后再压入栈,依此直到表达式尾部。
代码:

#include <bits/stdc++.h>
using namespace std;
map<char, pair<int, int>> matrix;
int main() {
    freopen("i.txt", "r", stdin);
    int n;
    cin >> n;
    string str;
    char ch;
    for(int i = 0; i < n; i++) {
        pair<int, int> p;
        cin >> ch >> p.first >> p.second;
        matrix[ch] = p;
    }
    while(cin >> str) {
        stack<char> stack1;
        bool flag = true;
        int sum = 0;
        for(int i = 0; i < str.length(); i++) {
            if(isalpha(str[i])) stack1.push(str[i]);
            if(str[i]==')') {
                char ch2 = stack1.top();
                stack1.pop();
                char ch1 = stack1.top();
                stack1.pop();
                if(matrix[ch1].second!=matrix[ch2].first)
                    flag = false;
                sum += matrix[ch1].first*matrix[ch2].first*matrix[ch2].second;
                stack1.push(ch1+26);
                matrix[ch1+26] = make_pair(matrix[ch1].first,matrix[ch2].second);
            }
        }
        if(flag)
            cout << sum << endl;
        else cout << "error" << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值