游客 Signup | Login
中文 | En

1811 - 表达式求值

通过次数

0

提交次数

0

Time Limit : 3 秒 Memory Limit : 128 MB

Dr.Kong设计的机器人卡多掌握了加减法运算以后,最近又学会了一些简单的函数求值,比如,它知道函数min(20,23)的值是20 ,add(10,98) 的值是108等等。经过训练,Dr.Kong设计的机器人卡多甚至会计算一种嵌套的更复杂的表达式。

假设表达式可以简单定义为:

1. 一个正的十进制数 x 是一个表达式。

2. 如果 和  表达式,则 函数min(x,y )也是表达式,其值为x,y 中的最小数。

3. 如果 和  表达式,则 函数max(x,y )也是表达式,其值为x,y 中的最大数。

4.如果 和  表达式,则 函数add(x,y )也是表达式,其值为x,y 之和。

例如, 表达式 max(add(1,2),7) 的值为 7

请你编写程序,对于给定的一组表达式,帮助 Dr.Kong 算出正确答案,以便校对卡多计算的正误

Input

第一行: N 表示要计算的表达式个数 (1≤ N ≤ 10)
接下来有N行, 每行是一个字符串,表示待求值的表达式
(表达式中不会有多余的空格,每行不超过300个字符,表达式中出现的十进制数都不
超过1000。)

Output

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

Examples

Input Format

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

Output Format

3
999
200

Solution C++

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ADD 1002
#define MIN 1003
#define MAX 1004
int optrStack[301],ptr;

int pop(){return optrStack[--ptr];}

void push(int n){optrStack[ptr++]=n;}

void readOptr(char *s,int &now){
    if(s[1]=='d')
        push(ADD);
    else if(s[1]=='i')
        push(MIN);
    else
        push(MAX);
    now+=4;
}

void readNum(char *s,int &now){
    int n,i=0;
    sscanf(s,"%d",&n);
    push(n);
    while(s[i]!=','&&s[i]!=')'){
        now++;
        i++;
    }
}

void operate(int &now){
    int a,b,opt;
    b=pop();
    a=pop();
    opt=pop();
    if(opt==ADD)
        push(a+b);
    else if(opt==MIN)
        push(a>b?b:a);
    else
        push(a<b?b:a);
    now++;
}

int main(){
    int n,len,i;
    char data[301];
    scanf("%d",&n);
    while(n--){
        scanf("%s",data);
        len=strlen(data);
        i=ptr=0;
        while(i<len){
            if(isalpha(data[i]))
                readOptr(&data[i],i);
            else if(isalnum(data[i]))
                readNum(&data[i],i);
            else if(data[i]==',')
                i++;
            else
                operate(i);
        }
        printf("%d\n",pop());
    }
}