基础课模板题:AcWing 3302. 表达式求值
表达式求值(栈)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
stack<char> op; //操作符栈
stack<int> num; //数字栈
void eval()
{
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
auto c = op.top(); op.pop();
int x;
if(c == '+') x = a + b;
else if(c == '-') x = a - b;
else if(c == 'x') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
int T;
cin >> T;
while (T -- )
{
string s;
cin >> s;
op = stack<char>();
num = stack<int>();
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'x', 2}, {'/', 2}}; //定义运算符优先级
for(int i = 0; i < s.size(); i ++ )
{
if(isdigit(s[i])) //是数,压入数字栈
{
int j = i, x = 0;
while(isdigit(s[j]) && j < s.size())
x = x * 10 + s[j ++ ] - '0';
num.push(x);
i = j - 1;
}
else if(s[i] == '(') //是左括号,压入操作符栈
{
op.push(s[i]);
}
else if(s[i] == ')') //是右括号,计算前面的数直到遇到左括号为止
{
while(op.top() != '(') eval();
op.pop(); //弹出左括号
}
else //是操作符
{
// 栈顶操作符优先级大于等于当前操作符优先级,则要先计算
while(op.size() && op.top() != '(' && pr[op.top()] >= pr[s[i]])
eval();
op.push(s[i]);
}
}
while(op.size()) eval();
if(num.top() == 24) puts("Yes");
else puts("No");
}
return 0;
}
附:
几个概念:
C++中的除法是向零取整
对于正数,向下取整和向零取整一样(即都是把小数舍掉,只保留整数),这里只讨论负数的情况
1.向零取整
举个例子:-3除以2结果本来应该是-1.5,但是向0取整后结果就是-1(不是-2,因为-1更靠近0)。也就是原始的算出来的数以靠近0的原则进行取舍。不遵循四舍五入。
2.向下取整
举个例子:-3 / 7
向下取整是-1
,即比其小的第一个数,但是因为C++
是向零取整,所以-3 / 7
在C++中的结果是0