CSP:二十四点
涉及知识点:逆波兰式,栈
满分代码
#include <bits/stdc++.h>
using namespace std;
// 逆波兰式
// 一个数字栈,一个符号栈,符号栈里,栈顶符号的优先级必须比当前运算符低,否则就弹出进行运算
int main()
{
int n;
cin >> n;
string s; // 表达式
stack<int> numSt; // 数字栈
stack<char> operSt; // 运算符栈
operSt.push('#'); // #为最低优先级
for (int i = 0; i <n; ++i)
{
cin >> s;
for (int j = 0; j < 7; ++j)
{
if (j % 2 == 0) // 数字
{
numSt.push(s[j] - '0');
}
else // 运算符
{
if (s[j] == '-' || s[j] == '+')
{
if (operSt.top() != '#')
{
while (operSt.top() != '#')
{
char oper = operSt.top();
operSt.pop();
int a = numSt.top();
numSt.pop();
int b = numSt.top();
numSt.pop();
// 需要弹出的4种情况
if (oper == '-')
{
numSt.push(b - a);
}
else if (oper == '+')
{
numSt.push(b + a);
}
else if (oper == 'x') {
numSt.push(b * a);
}
else {
numSt.push(b / a);
}
}
}
operSt.push(s[j]);
}
else
{
if (operSt.top() != '#')
{
while (operSt.top() == 'x' || operSt.top() == '/')
{
char oper = operSt.top();
operSt.pop();
int a = numSt.top();
numSt.pop();
int b = numSt.top();
numSt.pop();
if (oper == 'x') {
numSt.push(b * a);
}
else {
numSt.push(b / a);
}
}
}
operSt.push(s[j]);
}
}
}
while (operSt.top() != '#')
{
char oper = operSt.top();
operSt.pop();
int a = numSt.top();
numSt.pop();
int b = numSt.top();
numSt.pop();
if (oper == '-')
{
numSt.push(b - a);
}
else if (oper == '+')
{
numSt.push(b + a);
}
else if (oper == 'x')
{
numSt.push(b * a);
}
else
{
numSt.push(b / a);
}
}
if (numSt.top() == 24)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
numSt.pop();
}
return 0;
}