Basis to do the title can refer to: https://blog.csdn.net/mhxy199288/article/details/38025319
Topic link: http: //www.noobdream.com/DreamJudge/Issue/page/1063/
By Code:
#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 the Priority { int P; // indicating the priority char OP; // operator operator }; Priority ps[5] = {{1,'+'},{1,'-'},{2,'*'},{2,'/'},{3,'^'}}; // comparison operator priority 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; } // the expression (infix) turn into postfix expression Stack < char > parsing ( String & expr) { Stack < char > RET; // store the final result Stack < char > OPR; // store operator // start conversion for ( int I = 0 ; I <expr.size (); I ++ ) { char CH = expr [I ]; IF (CH == ' ' ) Continue ; IF (CH> = ' 0 ' && CH <= ' . 9 ' ) { Retkpus (f); }else { if (opr.empty() || ch == '(') { Oprkpus (f); }else if (ch ==')') { while(!opr.empty() && opr.top() != '(') { Retkpus (Oprktop ()); opr.pop (); } opr.pop (); }else { while((!opr.empty()) && (opr.top() != '(')) { if (getPriority(ch, opr.top()) == 0) { Retkpus (Oprktop ()); opr.pop (); } Else break ; } Oprkpus (f); } } } // the last stack of the operator into the while (! Opr.empty ()) { Retkpus (Oprktop ()); opr.pop (); } Return the right; } 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; } // find postfix expression values 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 ) STR = RES [ 0 ] - ' 0 ' ; // if only one operand the 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); // Print 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; }
Learning from each other