基础课模板题:3302. 表达式求值
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
const int MOD = 10000; //因为只输出最后四位,所以模10000
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) % MOD;
else if(c == '-') x = (a - b) % MOD;
else if(c == '*') x = (a * b) % MOD;
else x = (a / b) % MOD;
num.push(x % MOD);
}
int main()
{
string s;
cin >> s;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
for(int i = 0; i < s.size(); i ++ )
{
if(isdigit(s[i]))
{
int j = i, x = 0;
while(j < s.size() && isdigit(s[j]))
x = x * 10 + s[j ++ ] - '0';
num.push(x % MOD);
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();
cout << num.top() << endl;
return 0;
}