ACM篇:Uva 442 -- Matrix Chain Multiplication

stack

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;
const int N = 26;
int n;

int readchar()
{
    int ch;
    while ((ch=getchar()) != EOF)
        if (isalpha(ch))
            return ch;
}

struct Node
{
    int r;
    int c;
    Node (int r=0, int c=0)
    {
        this->r = r;
        this->c = c;
    }
};
Node matrix[N];

void read_matrix()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        int id = readchar() - 'A';
        scanf("%d%d", &matrix[id].r, &matrix[id].c);
    }
}

long long _calculate(char *s)
{
    Node x, y;
    stack<Node> e;
    long long ret = 0;

    for (char *p = s; *p; p++)
    {
        if (isalpha(*p))
            e.push(Node(matrix[*p-'A'].r, matrix[*p-'A'].c));
        else if (*p == ')')
        {
            y = e.top();
            e.pop();
            x = e.top();
            e.pop();

            if (x.c != y.r)
                return -1;

            ret += x.r * x.c * y.c;
            e.push(Node(x.r, y.c));
        }
    }
    return ret;
}
int main()
{
    long long ans;
    char exp[N * 100];

    read_matrix();
    while (scanf("%s", exp) == 1)
        ((ans = _calculate(exp)) == -1) ? (printf("error\n")) : (printf("%lld\n", ans));

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值