uestc data structure n 秋实大哥搞算数

来源:互联网 发布:越狱软件源 编辑:程序博客网 时间:2024/05/17 23:01

这道题本身没什么,就是两个栈计算表达式,但我一直re,原来是输入之间有空行导致的,,,,,吸取教训

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<stack>#define MAX 2000010using namespace std;char s[MAX];long long cal(long long a,long long b,char opt){if(opt=='+')return a+b;if(opt=='-')return a-b;if(opt=='*')return a*b;if(opt=='/')return a/b;}int main(){int n,len,start,flag;char ch;cin>>n;getchar();while(n--){len=0;while(1){ch=getchar();if(ch=='\n')break;elseif(ch>='0'&&ch<='9'||ch=='+'||ch=='-'||ch=='*'||ch=='/'){s[len++]=ch;}}if(len==0){n++;continue;}stack<long long>num;stack<char>opt;if(s[0]=='+'||s[0]=='-'){start=1;if(s[0]=='-')flag=1;elseflag=0;}else{flag=0;start=0;}for(int i=start;i<len;i++){if(s[i]>='0'&&s[i]<='9'){long long number=s[i]-'0';int j;for(j=i+1;j<len&&s[j]>='0'&&s[j]<='9';j++)number=number*10+s[j]-'0';i=j-1;if(flag){number=-number;flag=0;}num.push(number);}else if(s[i]=='*'||s[i]=='/'){while(!opt.empty()&&(opt.top()=='*'||opt.top()=='/')){long long b=num.top();num.pop();long long a=num.top();num.pop();char optr=opt.top();opt.pop();num.push(cal(a,b,optr));}opt.push(s[i]);}else if(s[i]=='+'||s[i]=='-'){while(!opt.empty()){long long b=num.top();num.pop();long long a=num.top();num.pop();char optr=opt.top();opt.pop();num.push(cal(a,b,optr));}opt.push(s[i]);}}while(!opt.empty()){long long b=num.top();num.pop();long long a=num.top();num.pop();char optr=opt.top();opt.pop();num.push(cal(a,b,optr));}cout<<num.top()<<endl;}return 0;}


0 0
原创粉丝点击