洛谷 - P1449

· · 个人记录

题意

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

本题中运算符仅包含 \texttt{+-*/}。保证对于 \texttt{/} 运算除数不为 0。特别地,其中 \texttt{/} 运算的结果需要向 0 取整(即与 C++ / 运算的规则一致)。

如:\texttt{3*(5-2)+7} 对应的后缀表达式为:\texttt{3.5.2.-*7.+@}。在该式中,@ 为表达式的结束符号。. 为操作数的结束符号。

思路

最后栈里剩下的一个元素即为答案。

(写快读写T了)

代码

#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
using namespace std;

const int N = 53;
int n;
string s;
int nb;

int st[N], stc;

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> s;
    n = s.size(), s = ' ' + s;

    for(int i = 1; i < n; i ++){
        if(s[i] == '.'){
            st[++ stc] = nb;
            nb = 0;
        }
        else if('0' <= s[i] && s[i] <= '9'){
            nb = nb * 10 + s[i] - '0';
        }
        else{
            if(s[i] == '+'){
                st[stc - 1] = st[stc - 1] + st[stc];
            }
            if(s[i] == '-'){
                st[stc - 1] = st[stc - 1] - st[stc];
            }
            if(s[i] == '*'){
                st[stc - 1] = st[stc - 1] * st[stc];
            }
            if(s[i] == '/'){
                st[stc - 1] = st[stc - 1] / st[stc];
            }
            stc --;
        }
    }

    cout << st[1];

    return 0;
}