CSP201903-2 二十四点

本文探讨了CSP(中国计算机学会)2019年第三轮的一个问题——二十四点游戏。通过深入解析游戏规则和算法思路,介绍了如何运用编程技巧来解决这一数学挑战,涉及搜索算法和组合优化策略。
摘要由CSDN通过智能技术生成
#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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值