在线着急,信奥栈1358!
  • 板块题目总版
  • 楼主niuchenyue
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/11/4 20:57
  • 上次更新2024/11/4 21:48:46
查看原帖
在线着急,信奥栈1358!
1407389
niuchenyue楼主2024/11/4 20:57

1358:中缀表达式值(expr)

时间限制: 1000 ms         内存限制: 65536 KB 提交数:15183    通过数: 5243 【题目描述】 输入一个中缀表达式(由0-9组成的运算数、加+减-乘*除/四种运算符、左右小括号组成。注意“-”也可作为负数的标志,表达式以“@”作为结束符),判断表达式是否合法,如果不合法,请输出“NO”;否则请把表达式转换成后缀形式,再求出后缀表达式的值并输出。

注意:必须用栈操作,不能直接输出表达式的值。

【输入】 一行为一个以@结束的字符串。

【输出】 如果表达式不合法,请输出“NO”,要求大写。

如果表达式合法,请输出计算结果。

【输入样例】 1+2*8-9@ 【输出样例】 8

#include<bits/stdc++.h>
using namespace std;
stack<int>num;
stack<char>expr;
char ch[32768];
int pri(char c){
	if(c=='-'||c=='+') return 1;
	else if(c=='*'||c=='/') return 2;
	else return 0;
}
void mate(){
	int top=0;
	for(int i=0;i<strlen(ch);i++){
		if(ch[i]=='(') top++;
		if(ch[i]==')') top--;
		if(top<0) break;
	}
	if(top!=0){
		cout<<"NO";
		exit(0);
	} 
}
void work(){
	if(num.empty()||expr.empty()){
		cout<<"NO";
		exit(0);
	}
	int a,b;
	a=num.top();
	num.pop();
	if(num.empty()){
		cout<<"NO";
		exit(0);
	}
	b=num.top();
	num.pop();
	char c;
	c=expr.top();
	expr.pop();
	if(c=='+') num.push(b+a);
	else if(c=='-') num.push(b-a);
	else if(c=='/'){
		if(a==0){
			cout<<"NO";
			exit(0);
		}
		num.push(b/a);
	}
	else if(c=='*') num.push(b*a);
}
int main(){
	int temp=0;
	bool flag=false;
	cin>>ch;
	mate();
	for(int i=0;i<strlen(ch)-1;i++){
		if(ch[i]>='0'&&ch[i]<='9'){
			temp=ch[i]-'0'+temp*10;
			flag=true;
		}
		else{
			if(flag){
				num.push(temp);
				temp=0;
				flag=false;
			}
			if(ch[i]=='('){
				expr.push(ch[i]);
				continue;
			}
			else if(ch[i]==')'){
				while(expr.top()!='('){
					work();
				}
				expr.pop();
				continue;
			}
			while(!expr.empty()&&pri(expr.top())>=pri(ch[i])){
				work();
			}
		}
		expr.push(ch[i]);
	}
	if(flag) num.push(temp);
	while(!expr.empty()){
		work();
	}
	cout<<num.top();
	return 0;
}

40分,在线着急!!!求解!!!

2024/11/4 20:57
加载中...