题解 | #矩阵乘法计算量估算# 双栈法

矩阵乘法计算量估算

https://www.nowcoder.com/practice/15e41630514445719a942e004edc0a5b

#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
using namespace std;

int main() {
    int n;
    cin >> n;
    // n * 2的输入
    vector<vector<int>> vec(n, vector<int>(2));
    for (int i = 0; i < n; i++) {
        cin >> vec[i][0] >> vec[i][1];
    }
    string rule;
    cin >> rule;
    // 双栈法
    stack<pair<int, int>> nums;
    stack<char> op;
    // 计算量累加
    int res = 0;
    // 两两计算栈中元素的计算量,直到栈元素为1
    auto compute = [&](stack<pair<int, int>> s) {
        while (s.size() != 1) {
            auto [a, b] = s.top();
            s.pop();
            auto [c, d] = s.top();
            s.pop();
            res += (a * d * c);
            auto tmp = std::make_pair(a, d);
            s.push(tmp);
        }
        return s.top();
    };
    // 标记字母对应的索引用于取维度值
    int idx = 0;
    for (int i = 0; i < rule.size(); i++) {
        int c = rule[i];
        if (std::isalpha(c)) {
            // 维度值入栈
            nums.push({vec[idx][0], vec[idx][1]});
            idx++;
            // 字母入操作栈
            op.push(c);
        } else {
            // 左括号入栈
            if (c == '(') {
                op.push(c);
            } else {
                // 将括号之间的矩阵运算按照正向顺序排列
                stack<pair<int, int>> tmps;
                while (op.top() != '(') {
                    tmps.push(nums.top());
                    nums.pop();
                    op.pop();
                }
                // '('出栈
                op.pop();
                // 将括号内的计算结果放入nums栈
                nums.push(compute(tmps));
                // 占位符,标记新放入的计算结果
                op.push('A');
            }
        }
    }
    cout << res << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

03-03 10:35
3d人士会梦见住进比弗利山庄吗:这四个项目属于是初学者的玩具了。不知道面试官咋问,而且双非本搞算法除了9,还是保守至少c9
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务