#include 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 stk; // 数字栈 stack op; // 操作符栈 // 优先级表 unordered_map 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); // 输出结果 }