栈(裸题)
来源:互联网 发布:ubuntu流量监控悬浮窗 编辑:程序博客网 时间:2024/05/19 02:44
Stack Aizu - ALDS1_3_A
Write a program which reads an expression in the Reverse Polish notation and prints the computational result.
An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106
Output
Print the computational result in a line.
Constraints
2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109
Sample Input 1
1 2 +
Sample Output 1
3
Sample Input 2
1 2 + 3 4 - *
Sample Output 2
-3
Notes
Template in C本题就是一个裸的栈问题,计算后缀表答式,具体后追表达式是什么就不清楚的讲了,网上很多,只要知道从右往左一次遍历,遇到一个符号就取出他的前两个数来计算,因为还存在括号这种情况所以会使用到栈。而我的代码则是用数组模拟栈,老实说我觉得STL的栈真的很慢。
简单题不多说,直接上代码:
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int maxn = 100 + 5;int top = 0;int S[1000];void push(int key){ S[++top] = key; return;}int pop(){ top--; return S[top+1];}int main(){ int a,b; top = 0; char s[maxn]; while(scanf("%s",s) != EOF){ if(s[0] == '+'){ a = pop(); b = pop(); push(a+b); } else if(s[0] == '-'){ b = pop(); a = pop(); push(a-b); } else if(s[0] == '*'){ a = pop(); b = pop(); push(a*b); } else{ push(atoi(s)); } } printf("%d\n",pop());}
这里的atio()是将字符转成数字的函数。
- 栈(裸题)
- 线段树(裸题)
- 队列(裸题)
- 链表(裸题)
- 裸题
- 裸题
- 裸题
- 裸题
- 假日的宿舍(裸题)
- [wikioi2930]填报志愿(裸题)
- LightOJ 1019 (FLoyd裸题)
- hdu1754(线段树)(裸题)
- Romantic(扩展欧几里得求逆元(裸题))
- hdu 3555(数位dp裸题)
- POJ 1789 Truck History (prime_裸题)
- poj3264 Balanced Lineup(RMQ裸题)
- POJ1287Networking(最小生成树,裸题)
- POJ3461:Oulipo(MP,KMP裸题)
- MySql避免重复插入记录方法(ignore,Replace,ON DUPLICATE KEY UPDATE)
- iOS swift - 通过xib 自定义View
- html 中textarea完整用法
- Arcgis学习之旅---基本概念
- Drawable子类——InsetDrawable
- 栈(裸题)
- 程序媛谈Java集合系列——总体框架
- C++读取注册表
- Android apk反编译
- JSP透过session判断用户是否登录
- Android.mk中的调试方法
- Vlan 中 Tag / Untag 报文处理
- 用lua扩展你的Nginx(写的非常好)
- try catch finally return 自增