標籤:pop contain values repeat get number symbols eof jpg
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
NotesTemplate in C
本題就是一個裸的棧問題,計算尾碼表答式,具體後追運算式是什麼就不清楚的講了,網上很多,只要知道從右往左一次遍曆,遇到一個符號就取出他的前兩個數來計算,因為還存在括弧這種情況所以會使用到棧。而My Code則是用數組類比棧,老實說我覺得STL的棧真的很慢。
簡單題不多說,直接上代碼:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 using namespace std; 6 7 const int maxn = 100 + 5; 8 9 int top = 0; 10 int S[1000]; 11 12 void push(int key){ 13 S[++top] = key; 14 return; 15 } 16 17 int pop(){ 18 top--; 19 return S[top+1]; 20 } 21 22 int main(){ 23 int a,b; 24 top = 0; 25 char s[maxn]; 26 while(scanf("%s",s) != EOF){ 27 if(s[0] == ‘+‘){ 28 a = pop(); 29 b = pop(); 30 push(a+b); 31 } 32 else if(s[0] == ‘-‘){ 33 b = pop(); 34 a = pop(); 35 push(a-b); 36 } 37 else if(s[0] == ‘*‘){ 38 a = pop(); 39 b = pop(); 40 push(a*b); 41 } 42 else{ 43 push(atoi(s)); 44 } 45 } 46 printf("%d\n",pop()); 47 }
棧(裸題)