https://www.luogu.com.cn/problem/P1449
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。
输入格式
输入:后缀表达式
输出格式
输出:表达式的值
输入输出样例
输入 #1复制
3.5.2.-*7.+@
输出 #1复制
16
说明/提示
字符串长度,1000内。
这道题是用栈进行实现,有一点需要注意:栈顶的操作数为operator2,栈顶的数弹出后的那个栈顶的操作数为operator1,进行运算时是 operator1 = operato1r operation operator2
代码:
#include <bits/stdc++.h>
#define MAXN 2000005
#define ll long long
ll n,m;
using namespace std;
stack<int> st;
int main()
{
string str;
cin>>str;
char opt;
int x,y;
int len,num,j;
len=str.length();
for(int i=0; i<len; i++)
{
if(str[i]=='@')
{
break;
}
if(str[i]=='.')
{
continue;
}
if(str[i]>='0'&&str[i]<='9')
{
num=0;
j=i;
for(j; j<len; j++)
{
if(str[j]>='0'&&str[i]<='9')
{
num = num*10 + str[j]-'0';
}else
{
break;
}
}
st.push(num);
//cout<<num<<endl;
i=j-1;
continue;
}else
{
opt = str[i];
x = st.top();st.pop();
y = st.top();st.pop();
// cout<<y<<" "<<x<<" "<<opt<<endl;
if(opt=='+')
{
y = y+x;
}else if(opt=='-')
{
y = y-x;
}else if(opt == '*')
{
y = y*x;
}else
{
y = y/x;
}
st.push(y);
}
}
cout<<st.top()<<endl;
return 0;
}