[河南省ACM省赛-第四届] 表达式求值(nyoj 305)
2015-04-01 21:02
393 查看
栈的模拟应用:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cstdlib> #include<algorithm> #include<stack> using namespace std; string getPostfixExp(string s) { stack<char> sta;// d n x string exp; int len = s.size(); for(int i=0; i<len; i++){ char ch = s[i]; if(ch == 'a' || ch == 'm') { //如果是字母 i += 2; sta.push(s[i]); } else if(ch == '('){ sta.push(ch); } else if(ch == ')'){//此时顶一定是( sta.pop();//弹走( exp += " "; exp += sta.top(); sta.pop(); } else if(ch != ','){ //数字 string num; while(s[i] >= '0' && s[i] <= '9'){ num += s[i++]; } if(exp[0] != NULL)//后缀表达式的第一个一定是数字,用此来避免首位空格 exp += " "; exp += num; i--; } } return exp; } int calculate(string post) { stack<int>sta; int len = post.size(); for(int i=0; i<len; i++){ int ch = post[i]; if(ch >= 'a') {//如果是运算符 int a = sta.top(); sta.pop(); int b = sta.top(); sta.pop(); if(ch == 'd') sta.push(a+b); else if(ch == 'x') sta.push(max(a, b)); else if(ch == 'n') sta.push(min(a, b)); } else if(ch != ' ') {//如果为数字 int num = 0; while(post[i] >= '0' && post[i] <= '9') num = num*10+post[i++]-'0'; sta.push(num); i--; } } return sta.top(); } int main() { freopen("d:\\in.txt", "r", stdin); string s; int t; cin>>t; while(t--) { cin>>s; string post = getPostfixExp(s); cout<<calculate(post)<<endl; } return 0; }
相关文章推荐
- NYOJ1272 表达式求值(后缀求值,特殊处理)(河南省第九届ACM省赛)
- NYOJ-305-表达式求值(第四届河南省程序设计大赛C题(模拟+栈||递归)(sscanf函数的应用))
- nyoj305表达式求值(第四届河南省程序设计大赛)
- 河南省第四届acm省赛 C:表达式求值 逆波兰表达式
- nyoj1272 zzulioj1923表达式求值(河南省acm第九届省赛)
- NYOJ 1272:表达式求值(2016河南省ACM-A)
- 河南省第四届acm省赛 表达式求值(栈的应用)
- 表达式求值(河南省第四届ACM试题-C题)题解
- [河南省ACM省赛-第四届] 序号互换 (nyoj 303)
- [河南省ACM省赛-第四届] Substring (nyoj 308)
- 【ACM】nyoj_305_表达式求值_201308081018
- [河南省ACM省赛-第四届] 走迷宫 (nyoj 306)
- noj 305 表达式求值 第四届河南省程序设计大赛//待续~~~
- nyoj 1272 表达式求值--河南省第九届省赛A题
- nyoj305-表达式求值(栈。。dfs)
- NYOJ,305,表达式求值
- 第四届省赛原题 表达式求值
- nyoj1278 zzuli1929 Prototypes analyze(河南省acm第九届省赛)
- NYOJ305_表达式求值
- NYOJ-305-表达式求值