站外题求助
  • 板块灌水区
  • 楼主roumeideclown
  • 当前回复4
  • 已保存回复4
  • 发布时间2023/5/31 13:10
  • 上次更新2023/10/23 14:15:24
查看原帖
站外题求助
830990
roumeideclown楼主2023/5/31 13:10

中缀表达式求值,有小括号,以@结尾

为什么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;
}

2023/5/31 13:10
加载中...