#3 #9 #10 这三个点RE了,能不能开放测试点数据下载。。。
查看原帖
#3 #9 #10 这三个点RE了,能不能开放测试点数据下载。。。
505294
Ted_Algorithm楼主2023/1/12 11:57
#include <bits/stdc++.h>
using namespace std;

string s,it;
stack<char> num,op;

bool check(char c){ //判断符号是否合法
	if (c<'0'||c>'9') return (c=='('||c==')'||c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
	return true;
}

int priority(char c){  //返回当前运算符的优先级 数字越大优先级越高
	if (c=='^') return 3;
	if (c=='*'||c=='/') return 2;
	if (c=='+'||c=='-') return 1;
	return -1;
}

void trans(){ //把栈里的所有运算数和运算符都倒序再输出,显示出中缀转后缀的表达式。
	while (!op.empty()){
		num.push(op.top());
		op.pop();
	}
	while (!num.empty()){
		op.push(num.top());
		num.pop();
	}
	while (!op.empty()){
		it=it+op.top()+' ';
		op.pop();
	}
}

int eval(stack<int> &stk,char c){ //后缀表达式计算
	int b=stk.top();
	stk.pop();
	int a=stk.top();
	stk.pop();
	if (c=='^') return pow(a,b);
	else if (c=='*') return a*b;
	else if (c=='/') return a/b;
	else if (c=='+') return a+b;
	else return a-b;
}

string prt(stack<int> &stk,string &it,int p){
	string res="";
	stack<int> t;
	while (!stk.empty()){
		t.push(stk.top());
		stk.pop();
	}
	while (!t.empty()){
		res=res+to_string(t.top())+' ';
		t.pop();
	}
	res=res+it.substr(p+2);
	return res;
}

int main(){
	cin>>s;
	for (int i=0;i<s.size();i++){
		if (!check(s[i])) continue;
		if (isdigit(s[i])) num.push(s[i]);  //如果当前是数字,那么直接把数字压入num栈
		else if (s[i]=='(') op.push(s[i]);  //如果是左括号( 放入op栈中 直到遇到右括号时将括号中的运算符都处理掉
		else if (s[i]==')'){
			while (op.top()!='('){
				num.push(op.top());
				op.pop();
			}
			op.pop();//最后要把左括号也弹出栈
		}
		else{
			//当op栈为空或者当前运算符优先级高于栈顶运算符时,此运算符入栈
			if (op.empty()) op.push(s[i]); 
			else{//当前运算符优先级小于等于栈顶运算符时,把栈顶运算符弹出放入num栈中
				if (priority(s[i])>priority(op.top())) op.push(s[i]);
				else if (priority(s[i])==priority(op.top())&&s[i]=='^') op.push(s[i]);
				else{
					while (!op.empty()&&priority(s[i])<=priority(op.top())){
						num.push(op.top());
						op.pop();
					}
					op.push(s[i]);
				}
			}
		}
	}
	trans();
	cout<<it<<endl; //完成第一部分
	//第二部分,开始后缀表达式计算,每算一个运算符输出一次当前的后缀表达式
	stack<int> stk;
	for (int i=0;i<it.size();i++){
		if (!check(it[i])) continue;
		if (isdigit(it[i])){
			int t=0;
			while (i<it.size()&&isdigit(it[i])) t=t*10+it[i++]-48;
			stk.push(t);
			i--;
		}
		else{
			int temp=eval(stk,it[i]);
			stk.push(temp);
			string ss=prt(stk,it,i);
			it=ss;
			cout<<it<<endl;
			i=-1;
		}
	}
	system("pause");
	return 0;
}

没有数据,调不出来,好难受啊 有没有大佬能帮忙看看,为啥会RE。

2023/1/12 11:57
加载中...