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 算出正确答案,以便校对卡多计算的正误。
3 add(1,2) max(1,999) add(min(1,1000),add(100,99))
3 999 200
解题思路:分类讨论,遇到什么符号分别进行什么样的操作。。。
#include <iostream> #include <cstdio> #include <cstring> #include <stack> using namespace std; int main() { int n; scanf("%d",&n); while(n--){ stack<char> s1; stack<int> s2; char a[305]; scanf("%s",a); int len=strlen(a); for(int i=0;i<len;i++){ if(a[i]==‘(‘||a[i]==‘,‘){ continue; } if(a[i]==‘m‘&&a[i+1]==‘a‘){ s1.push(‘1‘); i+=2; } if(a[i]==‘m‘&&a[i+1]==‘i‘){ s1.push(‘2‘); i+=2; } if(a[i]==‘a‘&&a[i+1]==‘d‘){ s1.push(‘3‘); i+=2; } if(a[i]>=‘0‘&&a[i]<=‘9‘){ int k=0; while(a[i]>=‘0‘&&a[i]<=‘9‘){ k=k*10+(a[i]-‘0‘); i++; } s2.push(k); i--; } if(a[i]==‘)‘){ int t1=s2.top(); s2.pop(); int t2=s2.top(); s2.pop(); if(s1.top()==‘1‘){ s1.pop(); s2.push(t1>t2?t1:t2); continue; } if(s1.top()==‘2‘){ s1.pop(); s2.push(t1<t2?t1:t2); continue; } if(s1.top()==‘3‘){ s1.pop(); s2.push(t1+t2); continue; } } } printf("%d\n",s2.top()); s2.pop(); } return 0; }
原文:http://www.cnblogs.com/TWS-YIFEI/p/5824556.html