?

P1981 [NOIP2013 普及组] 表达式求值

![](//图.tk/g1!25)
by cff_0102 @ 2023-07-05 13:30:58


?
by Ew_Cors @ 2023-07-05 13:52:42



by XQH0317 @ 2023-07-05 13:52:56


```cpp // 表达式求值 #include<iostream> #include<string> #include<map> #include<stack> #define int long long using namespace std; map<char, int> p; // 运算符的优先级 stack<int> nums; // 运算数栈 stack<char> op; // 运算符栈 void eval() // 进行一次运算 { int b = nums.top(); nums.pop(); // 后面的运算数更靠近栈顶,取出第2个运算数 int a = nums.top(); nums.pop(); // 前面的运算数更靠近栈底,取出第1个运算数 char c = op.top(); op.pop(); // 取出运算符 int ans = 0; // 运算的结果 if(c == '+') ans = a+b; // 处理加运算 else if(c == '-') ans = a-b; // 处理减运算 else if(c == '*') ans = a*b; // 处理乘运算 else if(c == '/') ans = a/b; // 处理除运算 nums.push(ans%10000); // 将结果入栈 } signed main() { p['+'] = 1, p['-'] = 1, p['*'] = 2, p['/'] = 2; // 初始化运算符的优先级,加减属于1级运算,乘除属于2级运算 string str; // 待求值的表达式 cin >> str; // 输入数据 for(int i=0;i<str.size();i++) // 遍历表达式并处理 { char c = str[i]; // 取出当前的字符 if(c >= '0' && c <= '9') // 如果当前为数字 { int j = i; // 指针 int x = 0; // 该运算数 while(j < str.size() && str[j] >= '0' && str[j] <= '9') // 向后继续读取当前的运算数 { x = x*10 + (str[j]-'0'); // 将char类型转换为int类型,并取出该运算数 j++; // 指针后移继续取 } i = j-1; // i更新至运算数的末尾,进行下一轮的向后处理 nums.push(x%10000); // 将运算数入栈 } else if(c == '(') op.push(c); // 左括号直接入栈 else if(c == ')') // 当前字符为右括号,则把上一个左括号到这里的运算全部处理 { while(op.top() != '(') eval(); // 处理运算 op.pop(); // 弹出左括号 } else { // 否则则为运算符,则现将前面的优先级更高的运算处理 // 如为左括号,则停止处理,以防对后面的右括号造成匹配错误 while(op.size() > 0 && op.top() != '(' && p[op.top()] >= p[c]) eval(); // 处理运算 op.push(c); // 把运算符入栈 } } while(op.size() > 0) eval(); // 处理栈中剩余数据 cout << nums.top()%10000; // 输出栈顶的结果 return 0; } ```
by _Coffice_ @ 2023-07-05 13:58:04


[正解](https://www.luogu.com.cn/paste/95d1kz76)
by Gohldg @ 2023-07-05 13:58:49


这个人我刚刚帮他看,然后一堆问题 最离谱是发现运算符栈是用int……
by Gohldg @ 2023-07-05 14:00:01


?
by YUSEIg @ 2023-07-05 14:00:12


?
by WA_sir @ 2023-07-05 14:02:41



by zwyyy @ 2023-07-05 18:40:26



by yee1024pi @ 2023-07-15 19:33:39


|