分析:
本题考察栈的基本应用-表达式求值,虽然不难,但是要想不用栈,直接模拟出先算乘除后算加减的过程也是不易的,过了样例提交不得分的情况也是很常见的,所以为了保险起见还是直接用栈模拟中缀表达式的计算过程。
首先,输入确保数字都是一位数,而且运算都只涉及加减乘除。我们维护一个操作数栈和一个操作符栈,遍历表达式,遍历到数时直接压入操作数栈即可;遍历到操作符时,当且仅当操作符栈非空且操作符栈顶元素的优先级大于等于遍历到的元素优先级时,才从操作数栈弹出两个操作数,同时弹出操作符栈的栈顶元素进行运算后将新的操作数压入操作数栈,最后将遍历到的操作符压入操作符栈。
注意:遍历完一遍表达式后,可能操作符栈还有操作符未进行运算,继续不断弹出操作符进行运算即可。
#include <iostream>
#include <cstdio>
#include <stack>
#include <cctype>
#include <cstring>
using namespace std;
int solve(int x,int y,char c){
switch(c){
case '+':
return x + y;
case '-':
return x - y;
case 'x':
return x * y;
case '/':
return x / y;
}
}
int main() {
int T;
cin >> T;
while (T--) {
char str[10];
stack<int> num;
stack<char> op;
scanf("%s", str);
int n = strlen(str);
int ans = 0;
for(int i = 0;i < n;i++){
if(i % 2){
if(op.size() && !(op.top() != 'x' && op.top() != '/' && (str[i] == 'x' || str[i] == '/')) ){
int y = num.top();
num.pop();
int x = num.top();
num.pop();
num.push(solve(x,y,op.top()));
op.pop();
}
op.push(str[i]);
}
else num.push(str[i] - '0');
}
while(op.size()){
int y = num.top();
num.pop();
int x = num.top();
num.pop();
num.push(solve(x,y,op.top()));
op.pop();
}
if (num.top() == 24) cout << "Yes" << endl;
else
{
cout << "No" << endl;
}
}
return 0;
}