要做该题的基础可以参考:https://blog.csdn.net/mhxy199288/article/details/38025319
题目链接:http://www.noobdream.com/DreamJudge/Issue/page/1063/
通过代码:
#include <iostream> #include <stack> #include <string> #include <queue> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #define ll long long using namespace std; string expr; struct Priority{ int p;// 表示优先级 char op;// 操作运算符 }; Priority ps[5] = {{1,'+'},{1,'-'},{2,'*'},{2,'/'},{3,'^'}}; // 比较运算符优先级 int getPriority(char a, char b) { int a1, b1; for (int i = 0; i < 5; i++) { if (ps[i].op == a) { a1 = ps[i].p; } if (ps[i].op == b) { b1 = ps[i].p; } } return a1 > b1 ? 1 : 0; } // 把表达式(中缀表达式)转成后缀表达式 stack<char> parsing(string &expr) { stack<char> ret;// 存放最终结果 stack<char> opr;// 存放运算符 // 开始转换 for (int i = 0; i < expr.size(); i++) { char ch = expr[i]; if (ch == ' ') continue; if (ch >= '0' && ch <= '9') { ret.push(ch); }else { if (opr.empty() || ch == '(') { opr.push(ch); }else if (ch ==')') { while(!opr.empty() && opr.top() != '(') { ret.push(opr.top()); opr.pop(); } opr.pop(); }else { while((!opr.empty()) && (opr.top() != '(')) { if (getPriority(ch, opr.top()) == 0) { ret.push(opr.top()); opr.pop(); }else break; } opr.push(ch); } } } // 把最后的运算符放到栈中 while(!opr.empty()) { ret.push(opr.top()); opr.pop(); } return ret; } ll cal(ll a, ll b, char op) { switch(op) { case '+': return a+b; break; case '-': return a-b; break; case '*': return a*b; break; case '/': return a/b; break; case '^': return pow(a, b); break; default: break; } } void print(stack<ll> s, string &str, int start) { vector<ll> ans; int i = 1; while(!s.empty()) { ans.push_back(s.top()); s.pop(); } for (i = ans.size()-1; i >= 0; i--) cout << ans[i] << " "; for (i = start; i < str.size(); i++) cout << str[i] << " "; cout << endl; } // 求后缀表达式的值 void getRes(string &expr) { stack<char> bls = parsing(expr); stack<ll> s; string str = ""; char ch; int a, b, res = 0; while(!bls.empty()) { str = bls.top() + str; bls.pop(); } if (str.size() == 1) res = str[0]-'0';// 如果只有一位运算数 else { for (int i = 0; i < str.size(); i++) { ch = str[i]; if (ch >= '0' && ch <= '9') s.push(ch-'0'); else { print(s, str, i);//打印 b = s.top(); s.pop(); a = s.top(); s.pop(); res = cal(a,b,ch); s.push(res); } } } cout << res << endl; } int main() { while(cin >> expr) { getRes(expr); } return 0; }
相互学习