中缀表达式求值,有小括号,以@结尾
为什么RE!
#include<bits/stdc++.h>
#pragma GCC optimeze(1)
#pragma GCC optimeze(2)
#pragma GCC optimeze(3,"Ofast","inline")
using namespace std;
stack<int> num;
stack<char> op;
string s;
void input() {
getline(cin,s);
return;
}
int calc(char _op,int x,int y) {
switch(_op) {
case '+':
return x+y;
break;
case '-':
return x-y;
break;
case '*':
return x*y;
break;
case '/' : {
return x/y;
break;
}
}
}
int work() {
for(int i=0;i<s.length()-1;i++) {
if(s[i]=='+'||s[i]=='-') {
if(op.empty()) {
op.push(s[i]);
}
else {
while(op.top()=='+'||op.top()=='-'||op.top()=='*'||op.top()=='/') {
char _op=op.top();
op.pop();
int a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
num.push(calc(_op,a,b));
}
op.push(s[i]);
}
}
else if(s[i]=='*'||s[i]=='/') {
if(op.empty()) {
op.push(s[i]);
}
else {
while(op.top()=='*'||op.top()=='/') {
char _op=op.top();
op.pop();
int a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
num.push(calc(_op,a,b));
}
op.push(s[i]);
}
}
else if(s[i]=='(') {
op.push(s[i]);
}
else if(s[i]==')') {
while(op.top()!='(') {
char _op=op.top();
op.pop();
int a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
num.push(calc(_op,a,b));
}
op.pop();
}
else {
num.push(s[i]-'0');
}
}
while(!op.empty()) {
char _op=op.top();
op.pop();
int a,b;
b=num.top();
num.pop();
a=num.top();
num.pop();
num.push(calc(_op,a,b));
}
return num.top();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
input();
int ans=work();
cout<<ans;
return 0;
}