NC212914 牛牛与后缀表达式

题目

题目描述

给定牛牛一个后缀表达式 \(s\) ,计算它的结果,例如,1+1对应的后缀表达式为1#1#+,‘#’作为操作数的结束符号。

其中,表达式中只含有‘+’、’-‘、’*‘三种运算,不包含除法。

本题保证表达式一定合法,且计算过程和计算结果的绝对值一定不会超过\(10^{18}\)

示例1

输入

"1#1#+"

返回值

2

说明

1#1#+这个后缀表达式表示的式子是1+1,结果为2

示例2

输入

"12#3#+15#*"

返回值

225

说明

12#3#+15#*这个后缀表达式表示的式子是(12+3)*15,结果为225

备注

\(1\leq表达式中操作数\leq10^9\)
\(1\leq表达式长度\leq10^6\)

题解

知识点:栈,模拟。

遍历字符串,如果是数字则转化存在 \(num\) 里直到遇到 \(\#\) 放入栈中并初始化;如果是其他符号则是运算符,判断类型并对应运算。要注意的是,从栈中提取数字是第二个数字到第一个数字提取,是反着的,对减法有影响。

时间复杂度 \(O(n)\)

空间复杂度 \(O(n)\)

代码

#include <bits/stdc++.h>
#define ll long long

using namespace std;

int main() {
    std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    string str;
    cin >> str;

    stack<ll> s;
    ll num = 0;
    for (auto c : str) {
        if ('0' <= c && c <= '9') num = num * 10 + c - '0';
        else if (c == '#') s.push(num), num = 0;
        else {
            ll b = s.top();//!注意栈顶的是后运算的
            s.pop();
            ll a = s.top();
            s.pop();
            if (c == '+') s.push(a + b);
            else if (c == '-') s.push(a - b);
            else if (c == '*') s.push(a * b);
        }
    }
    cout << s.top() << '\n';
    return 0;
}
posted @ 2022-07-01 23:42  空白菌  阅读(97)  评论(0)    收藏  举报