表达式求值(模拟)

匿名 (未验证) 提交于 2019-12-03 00:18:01

Description

:

x

min()

max()

add()

max(add(1,27

Input

N

300

1000

Output

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!