P1449 后缀表达式
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:
3*(5-2)+7
\texttt{3*(5-2)+7}
3*(5-2)+7 对应的后缀表达式为:
3.5.2.-*7.+@
\texttt{3.5.2.-*7.+@}
3.5.2.-*7.+@。在该式中,@
为表达式的结束符号。.
为操作数的结束符号。
输入格式
输入一行一个字符串 s s s,表示后缀表达式。
输出格式
输出一个整数,表示表达式的值。
样例 #1
样例输入 #1
3.5.2.-*7.+@
样例输出 #1
16
提示
数据保证, 1 ≤ ∣ s ∣ ≤ 50 1 \leq |s| \leq 50 1≤∣s∣≤50,答案和计算过程中的每一个值的绝对值不超过 1 0 9 10^9 109。
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-08-02 18:17:15
* @LastEditTime: 2022-08-02 18:39:47
*/
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e6;
string s;
int a,b;
int n,m;
stack<int> q;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> s;
for(int i = 0;i < s.length();i++){
if(s[i] == '@')
break;
else if(s[i] == '.'){
q.push(a);
a = 0;
b = 0;
}
else if(s[i] >= '0' && s[i] <= '9'){
a = b * 10 + s[i] - '0';
b = a;
}
else{
if(s[i] == '+'){
n = q.top();
q.pop();
m = q.top();
q.pop();
q.push(m + n);
}
if(s[i] == '-'){
n = q.top();
q.pop();
m = q.top();
q.pop();
q.push(m - n);
}
if(s[i] == '*'){
n = q.top();
q.pop();
m = q.top();
q.pop();
q.push(m * n);
}
if(s[i] == '/'){
n = q.top();
q.pop();
m = q.top();
q.pop();
q.push(m / n);
}
}
}
cout << q.top() << endl;
return 0;
}