CSP-201903-2-二十四点
解题代码
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <vector>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '-' || c == 'x' || c == '/';
}
int getPriority(char c) {
if (c == 'x' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
}
string infixToPostfix(const string& infix) {
string postfix;
stack<char> opStack;
for (char c : infix) {
if (c == ' ') continue;
if (isdigit(c)) {
postfix += c;
}
else if (c == '(') {
opStack.push(c);
}
else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
opStack.pop();
}
else if (isOperator(c)) {
while (!opStack.empty() && getPriority(opStack.top()) >= getPriority(c)) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
int calculatePostfix(const string& postfix) {
stack<int> valStack;
for (char c : postfix) {
if (isdigit(c)) {
valStack.push(c - '0');
}
else {
int right = valStack.top(); valStack.pop();
int left = valStack.top(); valStack.pop();
switch (c) {
case '+': valStack.push(left + right); break;
case '-': valStack.push(left - right); break;
case 'x': valStack.push(left * right); break;
case '/': valStack.push(left / right); break;
}
}
}
return valStack.top();
}
int n;
string expr;
int main()
{
cin >> n;
for (size_t i = 0; i < n; i++)
{
cin >> expr;
if (calculatePostfix(infixToPostfix(expr))==24)
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
}