思路:
其实,掌握了中缀转后缀和计算后缀表达式的原理以后,这种题很简单,而且他都没有括号和负号的干扰,就是我也没想到一开始检查错误半天检查不出来,今天一会儿就看出来了,又长记性了,写代码时要状态好些,思路清晰一点,减少粗心导致的错误。
这道题需要注意:乘法用小写x表示
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int n;
int g(char c) {
if (c == '+' || c == '-')return 1;
else return 2;
}
int f(int a, int b, char c) {
if (c == '+')return a + b;
if (c == '-')return a - b;
if (c == 'x')return a * b;
if (c == '/')return a / b;
}
int main()
{
cin >> n;
for (int j = 0; j < n; j++) {
string s;
cin >> s;
stack<char> sc;
stack<int> si;
for (int i = 0; i < s.size(); i++) {
if (i % 2 == 0) {
si.push(s[i]-'0');
}
else {
if (sc.empty())sc.push(s[i]);
else {
int p1 = g(s[i]);
int p2 = g(sc.top());
if (p1 <= p2) {
while (p1 <= p2) {
int b = si.top();
si.pop();
int a = si.top();
si.pop();
int x = f(a, b, sc.top());
si.push(x);
sc.pop();
if (sc.empty())break;
else p2 = g(sc.top());
}
sc.push(s[i]);
}else
sc.push(s[i]);
}
}
}
while (!sc.empty()) {
char c = sc.top();
sc.pop();
int b = si.top();
si.pop();
int a = si.top();
si.pop();
int x = f(a, b, c);
si.push(x);
}
if (si.top() == 24)cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}