#include<bits/stdc++.h>
using namespace std;
int n;
int calculate(int first, int second , char operation)
{
switch (operation)
{
case '+':
return first + second;
case '-':
return first - second;
case 'x':
return first * second;
case '/' :
return first / second;
}
}
int main()
{
cin >> n;
map<char,int> Priority; //操作符的优先级比较
Priority['+'] = 1; Priority['-'] = 1;
Priority['x'] = 2; Priority['/'] = 2;
vector<string> S(n,string());
for(int i = 0 ; i < n; ++i)
{
cin >> S[i];
cin.get(); //取出空白字符-----回车键 ,防止污染S[i+1]
}
for(int i = 0 ;i < n; ++i)
{
stack<int> number ; //数字栈
stack<char> oper; //操作符栈
string S1 = S[i];
int sum = 0;
for(int k = 0 ; k < 7; ++k)
{
if (S1[k] >= '0' && S1[k] <= '9')
{
number.push(S1[k] - '0'); //数字进栈
}
else if( S1[k] == '+' || S1[k] == '-' || S1[k] == 'x' || S1[k] == '/') //操作符判断是否该进栈
{
if (oper.size() == 0) //操作符栈为空,直接入栈
{
oper.push(S1[k]);
}
else if(Priority[S1[k]] > Priority[oper.top()]) //当前操作符优先级和栈顶操作符优先级进行比较
/*
当前操作符优先级大于栈顶操作符优先级,直接入栈,小于和等于时需要先进行下面的计算再入栈
*/
{
oper.push(S1[k]);
}
else if (Priority[S1[k]] <= Priority[oper.top()])
{
int num1 = number.top(); number.pop();
int num2 = number.top(); number.pop();
char vanishoper = oper.top(); oper.pop();
int num3 = calculate(num2,num1,vanishoper); //注意此处的num1和num2的顺序,在+和x的时候 没有问题,在-和/的时候就需要考虑顺序了
number.push(num3);
oper.push(S1[k]);
}
}
}
while(number.size() > 1 && !oper.empty()) //进行最终的运算
{
int num1 = number.top(); number.pop();
int num2 = number.top(); number.pop();
char vanishoper = oper.top(); oper.pop();
int num3 = calculate(num2,num1,vanishoper); ////注意此处的num1和num2的顺序,在+和x的时候 没有问题,在-和/的时候就需要考虑顺序了
number.push(num3);
}
sum = number.top(); number.pop();
if (sum == 24)
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
S1.clear(); //将S1清空,避免对下一个表达式造成干扰
}
return 0;
}
结果:
注意题目中的乘号,是个'x'。命题人真是个奇葩,我记得还有一次涉及到路径匹配的问题的时候,他们题目给的三个点是一个半省略号,就是英文状态下按住shift+字母键盘上方的6,然后删掉了一半。闻所未闻的路径表示,也是醉了。看看按照他们的输入到实际操作中,提示的什么:
直接用三个点不行吗,非得别出心裁,还不说明,鬼知道你这是怎么输出来的。