跳到正文

个人记录

记事本

_CMZ_Lychee_约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

gdgzoi.com

P2817计算后缀表达式的值※※※

题目:

Description 所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3∗(5–2)+73*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。‘ @’为表达式的结束符号。 ‘.’为操作数的结束符号。

3.5.2.−∗7.+@ 3.5.2.-*7.+@ =3.3.∗7.+@=3.3.*7.+@ =9.7.+@=9.7.+@ =16=16

Input 一行字符串(长度小于200),格式符合上述后缀表达式,只包含 数字、“+”、“-”、“*”、“.”和”@“符号 Output 表达式的值

错误代码:

C++
#include <bits/stdc++.h>
using namespace std;
string s;
int ans;
int t,cnt=1,num;
bool f=0;
int main(){
	cin>>s;
	int st[201],top=0;
	for(int i=0;i<s.size();i++){
		if(s[i]>='0'&&s[i]<='9'){
			num*=cnt;
			num+=s[i]-'0';
			cnt*=10;
			t++;
		}
		else{
			if(t){
				if(f)st[++top]=-num;
				else st[++top]=num;
			}
			//cout<<st[top]<<' '<<top<<' '<<endl;
			cnt=1;num=t=0;f=0;
			int a,b;
			if(top&&s[i]!='.'){
				a=st[top-1];b=st[top];
			}
			if(s[i]=='+'){
				ans=a+b;
				//cout<<a<<'+'<<b<<'='<<ans<<endl;
			}
			if(s[i]=='-'){
				if(s[i+1]<'0'||s[i+1]>'9'){
					ans=a-b;
					//cout<<a<<'-'<<b<<'='<<ans<<endl;
				}
				else{f=1;}
			}
			if(s[i]=='*'){
				ans=a*b;
				//cout<<a<<'*'<<b<<'='<<ans<<endl;
			}
			if(top&&s[i]!='.'&&f!=1){
				top--;
				st[top]=ans;
				//cout<<st[top]<<endl;
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}

思路/算法:

手打栈模拟

重点样例:

in:

代码
3.1.-2.*2.1.-2.*+@

out:

代码
0

ans:

代码
6
原文