跳到正文

个人记录

洛谷 - P1449

Chthohepta约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月29日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v1当前

题意

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

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

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

思路

  • 每一次遇到一个数,就放进栈里。
  • 每一次遇到一个运算符,就把栈顶的两个元素拿出来计算,再放进栈里。

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

(写快读写T了)

代码

C++
#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;
}
原文