表达式求值(模拟)

5 篇文章 0 订阅

Description

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 算出正确答案,以便校对卡多计算的正误。

Input

第一行: N        表示要计算的表达式个数 (1≤ N ≤ 10)  

 

接下来有N行,    每行是一个字符串,表示待求值的表达式

 

(表达式中不会有多余的空格,每行不超过300个字符,表达式中出现的十进制数都不

 

超过1000。)

Output

输出有N行,每一行对应一个表达式的值。

Sample Input

3
add(1,2)
max(1,999)
add(min(1,1000),add(100,99))

Sample Output

3
999
200

 

思路:像这一类的模拟一般是用stl中的栈来进行操作比较便捷,这道题就用2个栈来实现,可恨的是知道怎么做却总是做不对,模拟题真的恶心。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
#include<stack>
#include<queue>
#include<ctime>
#define LL long long
using namespace std;
char str[302];
int solve()
{
    int len=strlen(str);
    stack<int> sta;
    for(int i=len-1;i>=0;i--)
    {
       if(str[i]=='('||str[i]==')') 
       continue;
       if(isdigit(str[i]))//函数判断是否为数字 
       {
            int temp=str[i]-'0',k=1,l=i;
            while(isdigit(str[l-1]))
            {
                k*=10;
                temp+=(str[l-1]-'0')*k;
                l--;
            }
            i=l;
            sta.push(temp);
        }
        else if(str[i]=='d')
        {
           int a=sta.top();
           sta.pop();
           int b=sta.top();
           sta.pop();
           sta.push(a+b);
           i-=2;
        }
        else if(str[i]=='x')
        {
           int a=sta.top();
           sta.pop();
           int b=sta.top();
           sta.pop();
           sta.push(max(a,b));
           i-=2;
        }
        else if(str[i]=='n')
        {
           int a=sta.top();
           sta.pop();
           int b=sta.top();
           sta.pop();
           sta.push(min(a,b));
           i-=2;
        }
    }
    return sta.top();
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        printf("%d\n",solve());
    }
    return 0; 
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值