洛谷 P1449:后缀表达式 ← 数组模拟栈
【题目来源】
https://www.luogu.com.cn/problem/P1449
【题目描述】
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右进行(不用考虑运算符的优先级)。
本题中运算符仅包含 +-*/。保证对于 / 运算除数不为 0。特别地,其中 / 运算的结果需要向 0 取整(即与 C++ / 运算的规则一致)。
如:3*(5-2)+7 对应的后缀表达式为:3.5.2.-*7.+@。在该式中,@ 为表达式的结束符号。. 为操作数的结束符号。
【输入格式】
输入一行一个字符串 s,表示后缀表达式。
【输出格式】
输出一个整数,表示表达式的值。
【输入样例1】
3.5.2.-*7.+@
【输出样例1】
16
【输入样例2】
10.28.30./*7.-@
【输出样例2】
-7
【说明/提示】
数据保证,1≤∣s∣≤50,答案和计算过程中的每一个值的绝对值不超过 10^9。
【算法分析】
● 数组模拟栈:https://blog.csdn.net/hnjzsyjyj/article/details/130522133
● 如下代码,利用数组模拟栈,实现逆序输出。
#include <bits/stdc++.h>
using namespace std;const int maxn=105;
char s[maxn];int main() {char x;int top=0;int n;cin>>n;while(n--) {cin>>x;s[++top]=x;}while(top!=0) {cout<<s[top];top--;}return 0;
}/*
in:
5
abcdeout:
edcba
*/
【算法代码】
#include <bits/stdc++.h>
using namespace std;int a[55],top;int main() {char t=getchar();while(t!='@') {if(t>='0' && t<='9') {int num=0;while(t>='0' && t<='9') {num=num*10+(t-'0');t=getchar();}a[++top]=num;continue;}if(t=='+' || t=='-' || t=='*' || t=='/') {int x=a[top--], y=a[top--];switch(t) {case '+':a[++top]=y+x;break;case '-':a[++top]=y-x;break;case '*':a[++top]=y*x;break;case '/':a[++top]=y/x;break;}}t=getchar();}printf("%d",a[top]);return 0;
}/*
in:3.5.2.-*7.+@
out:16
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/130522133
https://www.luogu.com.cn/problem/solution/P1449
https://blog.csdn.net/hnjzsyjyj/article/details/145522672