题解 | 24点运算

24点运算

https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// 牌面转数值
int val(const string& s) {
    if (s == "J") return 11;
    if (s == "Q") return 12;
    if (s == "K") return 13;
    if (s == "A") return 1;
    return stoi(s);
}

// 运算函数
int calc(int a, int b, int op) {
    switch (op) {
        case 0:
            return a + b;
        case 1:
            return a - b;
        case 2:
            return a * b;
        default:
            return a / b; // op3为除法
    }
}

int main() {
    vector<string> cards(4);
    for (int i = 0; i < 4; ++i) cin >> cards[i];

    // 检查大小王
    for (auto& c : cards)
        if (c == "joker" || c == "JOKER") {
            cout << "ERROR";
            return 0;
        }

    vector<int> v;
    for (auto& c : cards) v.push_back(val(c)); // 数值数组
    char ops[4] = {'+', '-', '*', '/'}; // 运算符映射

    // 枚举4张牌的全排列(索引)
    for (int a = 0; a < 4; ++a)
        for (int b = 0; b < 4; ++b) if (b != a)
                for (int c = 0; c < 4; ++c) if (c != a && c != b)
                        for (int d = 0; d < 4; ++d) if (d != a && d != b && d != c)
                                // 枚举3个运算符(0-3对应+、-、*、/)
                                for (int o1 = 0; o1 < 4; ++o1)
                                    for (int o2 = 0; o2 < 4; ++o2)
                                        for (int o3 = 0; o3 < 4; ++o3) {
                                            // 从左到右计算
                                            int res = calc(calc(calc(v[a], v[b], o1), v[c], o2), v[d], o3);
                                            if (res == 24) {
                                                // 输出算式
                                                cout << cards[a] << ops[o1] << cards[b] << ops[o2] << cards[c] << ops[o3] <<
                                                     cards[d];
                                                return 0;
                                            }
                                        }

    cout << "NONE"; // 无解
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务