Expression
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 202 Accepted Submission(s): 61
Problem Description
As a shopkeeper of a restaurant,everyday ,dandelion‘s mother needs to calculate the incomes.Sometimes,she may make some mistakes.So dandelion wants you to write a program to help her calculate the value of some expressions. You may consider every expression is made of :left parenthesis ‘(‘ ,right parenthesis ‘)‘ , plus sign ‘+‘ , subtraction sign ‘-‘ , multiplication sign ‘*‘ ,positive sign ‘+‘ ,and negative sign ‘-‘.There is no precursor 0.The length of expression will not exceed 100.The value produced during the calculating will not exceed 10^9.Every expression is legal.Ie. ((10+(-100))) ,-(-1),-3*(+5+7*2)-(0) ,-0 ,(-3)*(-5+7) are legal,while 1+-7 ,--3+8 ,-3+() are illegal.
Input
There are several cases,every line contains a expression.
Output
For every case ,print the answer of the expression.
Sample Input
-3*(+5-7*2)-(0)
Sample Output
27
Author
dandelion
Source
栈的运用 考虑的比较多 使用 STL <stack>
详细的看注释
#include<bits/stdc++.h> using namespace std; char a[105]; stack<char> m;//运算符栈 stack<int> n;//操作室栈 map<char,int> mp; //40 ( //41 ) //42 * //43 + //45 - int main() { mp[‘-‘]=1; mp[‘+‘]=1; mp[‘*‘]=2; mp[‘(‘]=-1; mp[‘)‘]=-1; memset(a,0,sizeof(a)); while(gets(a)) { while(!m.empty()) m.pop(); while(!n.empty()) n.pop(); n.push(0);//考虑初始有符号 放在栈底 int len=strlen(a); int exm=0; int xx,yy; char what; for(int i=0; i<len; i++) { if(a[i]>=48&&a[i]<=57) exm=exm*10+a[i]-‘0‘; else { if(a[i]==‘(‘)// 前括号处理 添0 处理紧邻的符号 { m.push(a[i]); n.push(0); continue; } if(m.empty())//若运算符栈为空 { m.push(a[i]); continue; } else { if(mp[a[i]]>mp[m.top()]) //优先级大于栈顶运算符 m.push(a[i]); else {//直到优先级大于栈顶 或 栈空 或栈顶为后括号(这个没有验证) while(!m.empty()&&mp[a[i]]<=mp[m.top()]&&m.top()!=‘(‘)// 这里理解 { xx=n.top(); n.pop(); yy=n.top(); n.pop(); what=m.top(); m.pop(); if(mp[what]==1) { if(what==‘+‘) n.push(yy+xx); if(what==‘-‘) n.push(yy-xx); } if(mp[what]==2) n.push(yy*xx); } if(!m.empty()&&m.top()==‘(‘&&a[i]==‘)‘) //当前后括号相遇pop m.pop(); else //否则插入 m.push(a[i]); } continue; } } if(i>=1)//处理前括号后若无符号 { if(a[i-1]==‘(‘) n.pop(); } if(mp[a[i+1]]!=0)//判断exm 积累结束 { n.push(exm); exm=0; } if(i==len-1&&a[i]!=‘)‘)//考虑最后一个操作数 n.push(exm); } while(!m.empty())//直到 运算符栈空 { xx=n.top(); n.pop(); yy=n.top(); n.pop(); what=m.top(); m.pop(); if(mp[what]==1) { if(what==‘+‘) n.push(yy+xx); if(what==‘-‘) n.push(yy-xx); } if(mp[what]==2) n.push(yy*xx); } printf("%d\n",n.top());//输出栈顶值 memset(a,0,sizeof(a)); } return 0; }