[AcWing 3302] 表达式求值
2022/4/30 6:14:57
本文主要是介绍[AcWing 3302] 表达式求值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
点击查看代码
#include<iostream> #include<stack> #include<cstring> #include<unordered_map> using namespace std; stack<int> nums; stack<char> op; unordered_map<char, int> h{ {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} }; void eval() { int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); char p = op.top(); op.pop(); int r = 0; if (p == '+') r = a + b; if (p == '-') r = a - b; if (p == '*') r = a * b; if (p == '/') r = a / b; nums.push(r); } int main() { string s; cin >> s; for (int i = 0; i < s.size(); i ++) { if (isdigit(s[i])) { int x = 0, j = i; while (j < s.size() && isdigit(s[j])) { x = x * 10 + s[j] - '0'; j ++; } nums.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() && h[op.top()] >= h[s[i]]) eval(); op.push(s[i]); } } while (op.size()) eval(); cout << nums.top(); return 0; }
这篇关于[AcWing 3302] 表达式求值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain