思路:我们用一个栈存字符,一个栈存数字,由于左括号没有区分性,所以我们存MAX和MIN和ADD的最后一个字母,每当遇到右括号我们从数字栈中取出两个数字进行一次计算,且把逗号和代表左括号的字母删掉,把结果放入数字栈。
#include<bits/stdc++.h>
using namespace std;
int Calculation(int a,int b,char op)
{
switch(op)
{
case 'x': return max(a, b);
case 'n': return min(a, b);
case 'd': return a + b;
}
}
int main()
{
//ios::sync_with_stdio(false);
int T; cin >> T;
while (T--)
{
string s;
stack<int> opnd;
stack<char> optr;
cin >> s;
if (s.find('(') == string::npos)
{//只有一个数字
cout << s << endl;
continue;
}
s += '#';
optr.push('#');
int i = 0, num = 0;
bool flag = false;
while (s[i] != '#' || optr.top() != '#')
{
if (isdigit(s[i]))
{
num = num * 10 + s[i] - '0';
flag = true; i++;
continue;
}
else
{
if (flag)
{
opnd.push(num); num = 0; flag = false;
}
if (s[i] == 'm' || s[i] == 'a') i += 2;
switch(s[i])
{
case 'x'://MAX
case 'n'://MIN
case 'd'://ADD
case ',':
optr.push(s[i]);
break;
case ')':
if (optr.top() == 'x' || optr.top() == 'n' || optr.top() == 'd')
optr.pop();
else
{
optr.pop();
char op = optr.top(); optr.pop();
int num1 = opnd.top(); opnd.pop();
int num2 = opnd.top(); opnd.pop();
int ans = Calculation(num2, num1, op);
opnd.push(ans);
}
break;
}
i++;
}
}
cout << opnd.top() << endl;
}
return 0;
}
/*
10
add(1,2)
max(1,999)
add(min(1,1000),add(100,99))
add(min(min(3,2),1),max(44,add(30,5)))
*/