例6-3 uva 442

题目链接

https://vjudge.net/problem/UVA-442

题意:

已知 n ​ n​ n个矩阵的行和列,给出一系列矩阵相乘的表达式,求是否可以相乘,如果可以的话求相乘的次数。

思路

表达式问题一般也用栈来模拟。

本题中每两个矩阵相乘都有括号,如(AB)、((AB)C)而不会出现(ABC)。

因此左括号直接忽略,字母入栈,遇到右括号就把栈中两个元素相乘再入栈。

如果前一个矩阵的列和后一个矩阵的行不相等,则输出error。

AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
#include <vector>
#include <queue>
#include <stack>
#include <map>
using namespace std;
#define ll long long 
const int maxn = 100010;

struct Node {
    int row, col;
}node[30], n1, n2;
char s[maxn];

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    int n, len, x;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%s", s);
        x = s[0] - 'A';
        scanf("%d%d", &node[x].row, &node[x].col);
    }
    while(~scanf("%s", s)) {
        stack<Node> S;
        ll ans = 0;
        bool flag = true;
        len = strlen(s);
        for(int i = 0; i < len; i++) {
            if(s[i] == '(') continue;
            else if(s[i] == ')') {
                n2 = S.top();
                S.pop();
                n1 = S.top();
                S.pop();
                if(n1.col != n2.row) {
                    flag = false;
                    break;
                }
                else {
                    ans += n1.row * n1.col * n2.col;
                    n1.col = n2.col;
                    S.push(n1);
                }
            }
            else {
                S.push(node[s[i] - 'A']);
            }
        }
        if(flag)
            printf("%lld\n", ans);
        else
            printf("error\n");
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值