CCF二十四点

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

思路

方法一:非栈做法,加减法运算优先级相同,可以看做一种运算,乘除法同理,则最多一共判断 2 × 2 × 2 = 8 2\times2\times2=8 2×2×2=8种情况

#include <iostream>
using namespace std;
int n, a, b, c, d;
char x, y, z;
bool is_add(char m) {
    return m == '+' || m == '-';
}
int solve(int m, char op, int n) {
    switch(op) {
        case '+': return m + n;
        case '-': return m - n;
        case 'x': return m * n;
        case '/': return m / n;
    }
}
int judge() {
    if(is_add(x)) {
        if(is_add(y)) {
            if(is_add(z)) return solve(solve(solve(a, x, b), y, c), z, d);
            else return solve(solve(a, x, b), y, solve(c, z, d));
        } else {
            if(is_add(z)) return solve(solve(a, x, solve(b, y, c)), z, d);
            else return solve(a, x, solve(solve(b, y, c), z, d));
        }
    }
    if(is_add(y)) {
        if(is_add(z)) return solve(solve(solve(a, x, b), y, c), z, d);
        else return solve(solve(a, x, b), y, solve(c, z, d));
    }
    return solve(solve(solve(a, x, b), y, c), z, d);
}
int main() {
    for(scanf("%d", &n); n && ~scanf("%d%c%d%c%d%c%d", &a, &x, &b, &y, &c, &z, &d); n--) printf(judge() == 24 ? "Yes\n" : "No\n");
    return 0;
}

方法二:
栈的做法,不再赘述

#include <bits/stdc++.h>
using namespace std;
stack<int> si;
stack<char> sp;
int priority[128], n;
char s[10];
int calcul(int a, char op, int b) {
    switch(op) {
    case '+': return a + b;
    case '-': return a - b;
    case 'x':
    case '*':
        return a * b;
    case '/': return a / b;
    }
}
void step() {
    int y = si.top();
    si.pop();
    int x = si.top();
    si.pop();
    si.push(calcul(x, sp.top(), y));
    sp.pop();
}
int main() {
    priority['-'] = priority['+'] = 1;
    priority['*'] = priority['/'] = priority['x'] = 2;
    for(scanf("%d", &n); n-- && ~scanf("%s", s); ) {
        for(int i = 0; i < 7; i++) {
            if(isdigit(s[i])) si.push(s[i] - '0');
            else {
                while(!sp.empty() && priority[sp.top()] >= priority[s[i]]) step();
                sp.push(s[i]);
            }
        }
        while(!sp.empty()) step();
        printf(si.top() == 24 ? "Yes\n" : "No\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值