1. 程式人生 > >表示式求值(模擬)

表示式求值(模擬)

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; 
}