为什么会WA
  • 板块学术版
  • 楼主Fwio_
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/10 21:59
  • 上次更新2024/8/10 23:48:26
查看原帖
为什么会WA
965238
Fwio_楼主2024/8/10 21:59

题目 ,求表达式的值的题,没考虑负数之前拿了80pts,#1 RE,考虑负数之后60pts, #4#5 WA,但是自测数据都没问题,不清楚哪里有问题

#include<iostream>
#include<cstring>
#include<algorithm>
#include<stack>
#include<unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
stack<char> k;
string str;
int l , r;
unordered_map<char , int> priority{{'+' , 1} , {'-' , 1} , {'*' , 2} , {'/' , 2} , {'^' , 3}};
int qpow(int a , int n){
	int ans = 1;
	while(n){
		if(n & 1) ans *= a;
		n >>= 1;
		a *= a;
	}
	return ans;
}
void eval(){
	int y = num.top(); num.pop();
	int x = num.top(); num.pop();
	char z = op.top(); op.pop();
	if(z == '+') num.push(x + y);
	else if(z == '-') num.push(x - y);
	else if(z == '*') num.push(x * y);
	else if(z == '/') num.push(x / y);
	else if(z == '^') num.push(qpow(x , y));
}
int main(){
	cin >> str;
	for(auto i : str){
		if(i == '(') k.push(i);
		else if(i == ')'){
			if(k.empty()) l++;
			else k.pop();
		}
	}
	r += k.size();
	string L(l , '(') , R(r , ')');
	str.insert(0 , L) , str += R;
	string New;
	for(int i = 0;i < str.size();i++){
		if(str[i] == '-' || str[i] == '+'){
			if(i == 0) New += '0';
			else{
				if(str[i - 1] < '0' || str[i - 1] > '9') New += '0';
			}
		}
		New += str[i];
	}
	str = New;
	for(int i = 0;i < str.size();i++){
		if(str[i] >= '0' && str[i] <= '9'){
			int j = i;
			int g = 0;
			while(j < str.size() && str[j] >= '0' && str[j] <= '9') g = g * 10 + str[j++] - '0';
			num.push(g);
			i = j - 1;
		}
		else if(str[i] == '(') op.push(str[i]);
		else if(str[i] == ')'){
			while(!op.empty() && op.top() != '(') eval();
			op.pop();
		}
		else if(str[i] == '^') op.push(str[i]);
		else{
			while(!op.empty() && priority[op.top()] >= priority[str[i]]) eval();
			op.push(str[i]);
		}
	}
	while(!op.empty()) eval();
	cout << num.top() << endl;
	return 0;
}
2024/8/10 21:59
加载中...