#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
#include <vector>
using namespace std;
char op[] = {'+', '-', 'x', '/'};
int is_op(char ch){
for(int i = 0; i < 4; i++)
if(op[i] == ch)
return i;
return -1;
}
int cal(int a, int b, int id){
//printf("#### %d %c %d\n", a, op[id], b);
if(id == 0)
return a + b;
if(id == 1)
return a - b;
if(id == 2)
return a * b;
return a / b;
}
void fun(){
string f;
cin >> f;
vector<int> v; //10 + x means op[x]
for(int i = 0; i < f.length(); i++){
int x = is_op(f[i]);
if(x >= 0) v.push_back(10 + x);
else v.push_back(f[i] - '0');
}
stack<int> num;
stack<int> ops;
for(int i = 0; i < v.size(); i++){
//cout << "# " << v[i] << endl;
if(v[i] < 10){
num.push(v[i]);
continue;
}
int op = v[i] - 10;
if(ops.empty()){
ops.push(op);
continue;
}
int lst = ops.top();
if(op >= 2 && lst <= 1){
int n1 = num.top();
num.pop();
i++;
int n2 = v[i];
num.push(cal(n1, n2, op));
}else{
int n2 = num.top();
num.pop();
int n1 = num.top();
num.pop();
num.push(cal(n1, n2, ops.top()));
ops.pop();
ops.push(op);
}
}
int n1 = -1, n2 = -1, opp = 0, ans;
n2 = num.top();
num.pop();
if(num.empty()) ans = n2;
else{
opp = ops.top();
n1 = num.top();
num.pop();
ans = cal(n1, n2, opp);
}
//cout << ans << endl;
if(ans == 24) cout << "Yes";
else cout << "No";
}
int main(){
int n;
cin >> n;
if(!n) return 0;
fun();
n--;
while(n--){
cout << endl;
fun();
}
}
CSP201903-2 二十四点
最新推荐文章于 2022-06-28 08:16:17 发布
本文探讨了CSP(中国计算机学会)2019年第三轮的一个问题——二十四点游戏。通过深入解析游戏规则和算法思路,介绍了如何运用编程技巧来解决这一数学挑战,涉及搜索算法和组合优化策略。
摘要由CSDN通过智能技术生成