后缀表达式的值(信息学奥赛一本通-T1331)
生活随笔
收集整理的這篇文章主要介紹了
后缀表达式的值(信息学奥赛一本通-T1331)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目描述】
從鍵盤讀入一個后綴表達式(字符串),只含有0-9組成的運算數及加(+)、減(—)、乘(*)、除(/)四種運算符。每個運算數之間用一個空格隔開,不需要判斷給你的表達式是否合法。以@作為結束標志。
比如,16–9*(4+3)轉換成后綴表達式為:16□9□4□3□+*–,在字符數組A中的形式為:
棧中的變化情況:
運行結果:-47
提示:輸入字符串長度小于250,參與運算的整數及結果之絕對值均在2^64范圍內,如有除法保證能整除。
【輸入】
一個后綴表達式。
【輸出】
一個后綴表達式的值。
【輸入樣例】
16 9 4 3 +*-@
【輸出樣例】
-47
【源程序】
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<vector> #include<set> #include<map> #define PI acos(-1.0) #define E 1e-9 #define INF 0x3f3f3f3f #define LL long long const int MOD=1000000007; const int N=10000+5; const int dx[]= {-1,1,0,0}; const int dy[]= {0,0,-1,1}; using namespace std; char str[N]; stack<LL> S; int main(){gets(str);int len=strlen(str)-1;for(int i=0;i<len;i++){switch(str[i]){case '+':{LL y=S.top();S.pop();LL x=S.top();S.pop();S.push(x+y);break;}case '-':{LL y=S.top();S.pop();LL x=S.top();S.pop();S.push(x-y);break;}case '*':{LL y=S.top();S.pop();LL x=S.top();S.pop();S.push(x*y);break;}case '/':{LL y=S.top();S.pop();LL x=S.top();S.pop();S.push(x/y);break;}case '@':i=len;break;default:{LL temp=0;while(str[i]!=' ')temp=temp*10+str[i]-'0',i++;S.push(temp);break;}}}cout<<S.top()<<endl;return 0; }總結
以上是生活随笔為你收集整理的后缀表达式的值(信息学奥赛一本通-T1331)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动态规划 —— 背包问题 P08 ——
- 下一篇: 释放囚犯(洛谷-P1622)