题目链接:https://www.luogu.com.cn/problem/P1449
知识点是单调栈,但我们首先要弄清除,啥是后缀表达式
简单举个栗子:
3-2
后缀表达式为:
3 2 -
思路:
如果碰到数值,就压入栈。如果碰到运算符号,则依次取两次栈顶,运算之后再将结果压进栈中。
注意:进行减法或除法运算时,第一次取得栈顶的值作为减数或者除数。
这里先直接进行字符串输入,再依次将数字字符整合成整型,对于运算字符,采取分别判断。
代码如下:
#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<long long> st;
int main ( )
{
string ans;
long long x = 0, a, b;
int i, n;
cin >> ans;
n = ans.length ( ) - 1;
for ( i; i < n; ++ i )
{
if ( ans[ i ] >= '0' && ans[ i ] <= '9' )
{
x = x * 10 + ( ans[ i ] - '0' );
}
else if ( ans[ i ] == '.' )
{
st.push ( x );
x = 0;
}
else
{
if ( ans[ i ] == '+' )
{
a = st.top();
st.pop( );
b = st.top ( );
st.pop( );
st.push ( a + b );
}
else if ( ans[ i ] == '-' )
{
a = st.top();
st.pop( );
b = st.top ( );
st.pop( );
st.push ( b - a );
}
else if ( ans[ i ] == '*' )
{
a = st.top();
st.pop( );
b = st.top ( );
st.pop( );
st.push ( a * b );
}
else
{
a = st.top();
st.pop( );
b = st.top ( );
st.pop( );
st.push ( b / a );
}
}
}
x = st.top ( );
printf ( "%lld\n", x );
return 0;
}