栈的应用..

uva 442

  • 运算顺序不是很清晰,但是用栈来处理,就变得明了
  • 核心步骤是,把矩阵按运算顺序压入栈中,如果遇到就从栈中取出两个运算,将结果压回,这样就集成了括号带来的运算顺序。
#include <iostream>
#include <map>
#include <stack>
#include <fstream>
#include <string>

#define TEST 0

using namespace std;

typedef pair<int, int> Matrix;

int cnt;
bool compute(Matrix &, Matrix &, Matrix &);

int main()
{
    ofstream ofs;

    if (TEST)
    {
        ofs.open("/home/lixiaoqi/Documents/Code/C++/1.txt");
        if (!ofs.is_open())
            throw runtime_error("FILE NOT OPEN!");
    }
    ostream &os = TEST ? ofs : cout;

    char c;
    bool OK;
    int N, a, b;
    Matrix matrix[26];

    stack<Matrix> s;

    cin >> N;
    while (N--)
    {
        getchar();
        c = getchar();
        cin >> a >> b;
        matrix[c - 'A'] = make_pair(a, b);
    }

    getchar();
    while (cin >> c)
    {
        cnt = 0;
        OK = true;
        while ((c = getchar()) != '\n')
        {
            if (!OK)
                continue;
            if (c == ')')
            {
                Matrix B = s.top();
                s.pop();
                Matrix A = s.top();
                s.pop();
                Matrix _new;
                OK = compute(A, B, _new);
                if (OK)
                    s.push(_new);
            }
            else if (isalpha(c))
                s.push(matrix[c - 'A']);
        }
        os << (OK ? to_string(cnt) : "error") << '\n';
    }

    return 0;
}

bool compute(Matrix &a, Matrix &b, Matrix &ret)
{
    if (a.second != b.first)
        return false;
    cnt += a.first * a.second * b.second;
    ret.first = a.first;
    ret.second = b.second;
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值