思路
方法一:非栈做法,加减法运算优先级相同,可以看做一种运算,乘除法同理,则最多一共判断 2 × 2 × 2 = 8 2\times2\times2=8 2×2×2=8种情况
#include <iostream>
using namespace std;
int n, a, b, c, d;
char x, y, z;
bool is_add(char m) {
return m == '+' || m == '-';
}
int solve(int m, char op, int n) {
switch(op) {
case '+': return m + n;
case '-': return m - n;
case 'x': return m * n;
case '/': return m / n;
}
}
int judge() {
if(is_add(x)) {
if(is_add(y)) {
if(is_add(z)) return solve(solve(solve(a, x, b), y, c), z, d);
else return solve(solve(a, x, b), y, solve(c, z, d));
} else {
if(is_add(z)) return solve(solve(a, x, solve(b, y, c)), z, d);
else return solve(a, x, solve(solve(b, y, c), z, d));
}
}
if(is_add(y)) {
if(is_add(z)) return solve(solve(solve(a, x, b), y, c), z, d);
else return solve(solve(a, x, b), y, solve(c, z, d));
}
return solve(solve(solve(a, x, b), y, c), z, d);
}
int main() {
for(scanf("%d", &n); n && ~scanf("%d%c%d%c%d%c%d", &a, &x, &b, &y, &c, &z, &d); n--) printf(judge() == 24 ? "Yes\n" : "No\n");
return 0;
}
方法二:
栈的做法,不再赘述
#include <bits/stdc++.h>
using namespace std;
stack<int> si;
stack<char> sp;
int priority[128], n;
char s[10];
int calcul(int a, char op, int b) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case 'x':
case '*':
return a * b;
case '/': return a / b;
}
}
void step() {
int y = si.top();
si.pop();
int x = si.top();
si.pop();
si.push(calcul(x, sp.top(), y));
sp.pop();
}
int main() {
priority['-'] = priority['+'] = 1;
priority['*'] = priority['/'] = priority['x'] = 2;
for(scanf("%d", &n); n-- && ~scanf("%s", s); ) {
for(int i = 0; i < 7; i++) {
if(isdigit(s[i])) si.push(s[i] - '0');
else {
while(!sp.empty() && priority[sp.top()] >= priority[s[i]]) step();
sp.push(s[i]);
}
}
while(!sp.empty()) step();
printf(si.top() == 24 ? "Yes\n" : "No\n");
}
return 0;
}