CCF 201903-2 二十四点
//
// Created by asimov on 2020/3/20.
//CCF
//201903-2 二十四点
//
#ifndef CSP_24P_H
#define CSP_24P_H
#endif //CSP_24P_H
#include <bits/stdc++.h>
using namespace std;
stack<int> numStack;//操作数栈
stack<char> operationStack;//操作符栈
string str;
int p() {
int n, front, back, i, j;
cin >> n;
getchar(); //读取换行符,易漏!!!
for (i = 0; i < n; i++) {
while (!numStack.empty()) numStack.pop();//清空栈
while (!operationStack.empty()) operationStack.pop();
cin >> str;//读取字符串
//cout<<str.length()<<endl;
for (j = 0; j < str.length(); j++) {
if (str[j] >= '0' && str[j] <= '9')//若为数字,压入nd栈中
{
numStack.push(str[j] - '0');
} else if (str[j] == '+') //若为'+',压入op栈中
{
operationStack.push('+');
} else if (str[j] == '-')//转化为"+"计算(即将正数存储为负数,而op栈中就可以存放'+'了)
{
numStack.push((str[j + 1] - '0') * (-1));
operationStack.push('+');
j++;
} else if (str[j] == 'x')//先乘除法,与下一个未压入栈的数字计算,将计算结果压入数栈;
{
front = numStack.top();
numStack.pop();
back = str[j + 1] - '0';
numStack.push(front * back);
j++;//已经使用了后一位操作数 因此跳过
} else if (str[j] == '/') {
front = numStack.top();
numStack.pop();
back = str[j + 1] - '0';
numStack.push(front / back);
j++;
}
}
while (!operationStack.empty())//此时只剩下'+'未计算了
{
// 取两个操作数
front = numStack.top();
numStack.pop();
back = numStack.top();
numStack.pop();
operationStack.pop();
numStack.push(front + back);
}
// cout<<numStack.top()<<endl;
if (numStack.top() == 24)//取出栈中数字,看是否=24
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
/*
10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5
*/