1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include<cstdio> #include<stack> #include<queue> #include<map> #include<cctype> using namespace std; map<char,int> inop,outop; struct node{ int num; char oper; bool flag; node(){ num = 0; } }; queue<node> q; stack<node> s,ans; char str[210]; void infix(){ for (int i = 0; str[i] != '\0';) { node temp; if (isdigit(str[i])) { temp.flag = true; for (; isdigit(str[i])&& str[i] != '\0'; ++i) { temp.num = temp.num*10+str[i]-'0'; } q.push(temp); }else{ temp.flag = false; if (str[i]=='(') { temp.oper='('; s.push(temp); } else if (str[i]==')') { while(s.top().oper!='('){ q.push(s.top()); s.pop(); } s.pop(); }else{ while(!s.empty()&&inop[s.top().oper]>=outop[str[i]]){ q.push(s.top()); s.pop(); } temp.oper = str[i]; s.push(temp); } i++; } } while(!s.empty()){ q.push(s.top()); s.pop(); } } int main(){ freopen("A0721.txt","r",stdin); scanf("%s",str); inop['('] = 1; inop['*'] = 5; inop['/'] = 5; inop['+'] =3; inop['-'] =3; inop[')'] = 6; outop['(']= 6; outop['*'] =4; outop['/'] =4; outop['+'] =2; outop['-']= 2;outop[')'] = 1; infix();
while(!q.empty()){ node top = q.front(); q.pop(); if (top.flag==true) { ans.push(top); } else{ int b = ans.top().num; ans.pop(); int a = ans.top().num; ans.pop();
node temp; temp.flag = true; if (top.oper == '+'){ temp.num = a+b; } if (top.oper == '-'){ temp.num = a-b; } if (top.oper == '*'){ temp.num = a*b; } if (top.oper == '/'){ temp.num = a/b; } ans.push(temp); } } printf("%d\n",ans.top().num); return 0; }
|