二十四点(https://sim.csp.thusaac.com/contest/16/problem/1)

link

#include <bits/stdc++.h>

using namespace std;

stack<int> num;
stack<char> op;

void eval(){
    int b = num.top(); num.pop();
    int a = num.top(); num.pop();
    char c = op.top(); op.pop();
    
    int x;
    if(c == '+') x = a + b;
    else if(c == '-') x = a - b;
    else if(c == 'x') x = a * b;
    else{
        if(a * b >= 0) x = a / b;
        else{
            if(a % b == 0) x = a / b;
            else x = a / b - 1;
        }
    }
    num.push(x);
}

signed main(){
    int n;  cin >> n;
    
    unordered_map<char, int> mp;
    mp['+'] = mp['-'] = 1;
    mp['x'] = mp['/'] = 2;
    
    while(n--){
        num = stack<int>();
        op = stack<char>();
        
        string s; cin >> s;
        for(auto &x : s){
            if(x >= '0' && x <= '9') num.push(x - '0');
            else{
                while(op.size() && mp[op.top()] >= mp[x]) eval();
                op.push(x);
            }
        }
        while(op.size()) eval();
        
        if(num.top() == 24) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    
    return 0;
}
n = (int)(input())

# 使用python自带eval()函数
while n:
    n -= 1
    res = eval(input().replace('x', '*').replace('/', '//'))
    if res == 24:
        print("Yes")
    else: print("No")
posted @ 2025-02-28 13:49  awei040519  阅读(5)  评论(0)    收藏  举报