You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
// 因为要对10000取模注意在表达式求值模板的基础上不断取模要考虑乘法加法导致的int溢出问题开long long解决。
#define int long long
const int MOD = 10000;
/*
I
(2+2)*(1+1)
8
II
2+(3*4)-((5*9-5)/8-4)
13
*/
stack<int> stk; // 数字栈
stack<char> op; // 操作符栈
// 优先级表
unordered_map<char, int> g{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
/**
*
*/
void eval() {
int a = stk.top(); // 第二个操作数
stk.pop();
int b = stk.top(); // 第一个操作数
stk.pop();
char p = op.top(); // 运算符
op.pop();
int r; // 结果
// 计算结果
if (p == '+') r = (b + a) % MOD;
if (p == '-') r = (b - a) % MOD;
if (p == '*') r = (b * a) % MOD;
if (p == '/') r = (b / a) % MOD;
// 结果入栈
stk.push(r);
}
signed main() {
// 读入表达式
string s;
cin >> s;
// 遍历字符串的每一位
for (int i = 0; i < s.size(); i++) {
// ① 如果是数字,则入栈
if (isdigit(s[i])) {
// 读出完整的数字
int x = 0;
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
x = x * 10 + s[i] - '0';
i++;
}
i--; // 加多了一位,需要减去
stk.push(x % MOD); // 数字入栈
}
// ② 左括号无优先级,入栈
else if (s[i] == '(')
op.push(s[i]);
// ③ 右括号时,需计算最近一对括号里面的值
else if (s[i] == ')') {
// 从栈中向前找,一直找到左括号
while (op.top() != '(') eval(); // 将左右括号之间的计算完,维护回栈里
// 左括号出栈
op.pop();
} else { // ④ 运算符
// 如果待入栈运算符优先级低,则先计算
while (op.size() && g[op.top()] >= g[s[i]]) eval();
op.push(s[i]); // 操作符入栈
}
}
while (op.size()) eval(); // ⑤ 剩余的进行计算
printf("%d\n", stk.top() % MOD); // 输出结果
}