nyoj305表达式求值(数据结构---栈)
2015-04-30 20:59
239 查看
表达式求值
时间限制:3000 ms | 内存限制:65535 KB难度:3
描述
Dr.Kong设计的机器人卡多掌握了加减法运算以后,最近又学会了一些简单的函数求值,比如,它知道函数min(20,23)的值是20 ,add(10,98) 的值是108等等。经过训练,Dr.Kong设计的机器人卡多甚至会计算一种嵌套的更复杂的表达式。
假设表达式可以简单定义为:
1. 一个正的十进制数 x 是一个表达式。
2. 如果 x 和 y 是 表达式,则 函数min(x,y )也是表达式,其值为x,y 中的最小数。
3. 如果 x 和 y 是 表达式,则 函数max(x,y )也是表达式,其值为x,y 中的最大数。
4.如果 x 和 y 是 表达式,则 函数add(x,y )也是表达式,其值为x,y 之和。
例如, 表达式 max(add(1,2),7) 的值为 7。
请你编写程序,对于给定的一组表达式,帮助 Dr.Kong 算出正确答案,以便校对卡多计算的正误。
输入第一行: N 表示要计算的表达式个数 (1≤ N ≤ 10)
接下来有N行, 每行是一个字符串,表示待求值的表达式
(表达式中不会有多余的空格,每行不超过300个字符,表达式中出现的十进制数都不
超过1000。)
输出输出有N行,每一行对应一个表达式的值。
样例输入
3 add(1,2) max(1,999) add(min(1,1000),add(100,99))
样例输出
3 999 200
#include<stdio.h> #include<string.h> #include<cctype> #include<stack> #include<algorithm> using namespace std; char str[305]; int t; int deal() { stack<char>optch; stack<int>optnum; int a,b; int len=strlen(str); while(!optch.empty()) { optch.pop(); } while(!optnum.empty()) { optnum.pop(); } for(int i=0;i<len;) { if(isalpha(str[i])) { optch.push(str[i+1]); i+=4;//跳过'(' } else if(isdigit(str[i])) { a=0; b=0; while(isdigit(str[i])) { a=a*10+(str[i]-'0'); ++i; } optnum.push(a); } else if(str[i]==')')//每次遇到')' 就计算一次 { a=optnum.top(); optnum.pop(); b=optnum.top(); optnum.pop(); switch(optch.top()) { case 'd': optnum.push(a+b); ++i; break; case 'i': optnum.push(a<b?a:b); ++i; break; case 'a': optnum.push(a>b?a:b); ++i; break; } optch.pop(); } else ++i; } return optnum.top(); //optnum.pop(); } int main() { scanf("%d",&t); getchar(); while(t--) { scanf("%s",str); printf("%d\n",deal()); } return 0; }
相关文章推荐
- NYOJ-305-表达式求值
- NYOJ 305 表达式求值 (递归)
- NYOJ-35-表达式求值(C语言数据结构)
- nyoj 305 表达式求值
- 回顾 ——表达式求值——NYOJ305
- NYOJ-305-表达式求值-2013年8月8日10:44:12
- nyoj305-表达式求值(栈。。dfs)
- 表达式求值(nyoj305)
- NYOJ-305 表达式求值
- nyoj 305 表达式求值
- nyoj305 表达式求值(递归)
- nyoj305 表达式求值
- 数据结构--栈的应用(表达式求值 nyoj 35)
- NYOJ-305 表达式求值(模拟)
- NYOJ 305 表达式求值
- 【ACM】nyoj_305_表达式求值_201308081018
- NYOJ 305 表达式求值
- nyoj305表达式求值 栈的应用
- nyoj 305 表达式求值
- 南阳oj 表达式求值 题目305 数据结构