暴力解法, 任何时候都能写出来
/* * Created by JoeTim on 2021/6/30. */ #include <bits/stdc++.h> using namespace std; // 3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER bool dfs(int abc, int d, string &res) { if (abc + d == 24) { res.push_back('+'); return true; } if (abc - d == 24) { res.push_back('-'); return true; } if (abc * d == 24) { res.push_back('*'); return true; } if (abc / d == 24) { res.push_back('/'); return true; } return false; } bool dfs(int ab, int c, int d, string &res) { if (dfs(ab + c, d, res)) { res.push_back('+'); return true; } if (dfs(ab - c, d, res)) { res.push_back('-'); return true; } if (dfs(ab * c, d, res)) { res.push_back('*'); return true; } if (dfs(ab / c, d, res)) { res.push_back('/'); return true; } return false; } bool dfs(int a, int b, int c, int d, string &res) { if (dfs(a + b, c, d, res)) { res.push_back('+'); return true; } if (dfs(a - b, c, d, res)) { res.push_back('-'); return true; } if (dfs(a * b, c, d, res)) { res.push_back('*'); return true; } if (dfs(a / b, c, d, res)) { res.push_back('/'); return true; } return false; } int main() { unordered_map<string, int> CARD_MAP = { {"A", 1}, {"2", 2}, {"3", 3}, {"4", 4}, {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8}, {"9", 9}, {"10", 10}, {"J", 11}, {"Q", 12}, {"K", 13}, {"joker", -1}, {"JOKER", -2} }; unordered_map<int, string> CARD_INT_TO_STRING_MAP; for (auto it : CARD_MAP) { CARD_INT_TO_STRING_MAP[it.second] = it.first; } string s1, s2, s3, s4; while (cin >> s1 >> s2 >> s3 >> s4) { vector<int> nums = {CARD_MAP[s1], CARD_MAP[s2], CARD_MAP[s3], CARD_MAP[s4]}; int a(CARD_MAP[s1]), b(CARD_MAP[s2]), c(CARD_MAP[s3]), d(CARD_MAP[s4]); if (a <= 0 || b <= 0 || c <= 0 || d <= 0) { cout << "ERROR" << endl; continue; } int target = 24; int cur = 0; string res; bool isFlat = false; for (int i = 0; i < 4; ++i) { if (isFlat) break; for (int j = 0; j < 4; ++j) { if (isFlat) break; for (int k = 0; k < 4; ++k) { if (isFlat) break; for (int l = 0; l < 4; ++l) { if (isFlat) break; if (i == j || i == k || i == l || j == k || j == l || k == l) continue; if (dfs(nums[i], nums[j], nums[k], nums[l], res)) { printf("%s%c%s%c%s%c%s\n", CARD_INT_TO_STRING_MAP[nums[i]].c_str(), res[2], CARD_INT_TO_STRING_MAP[nums[j]].c_str(), res[1], CARD_INT_TO_STRING_MAP[nums[k]].c_str(), res[0], CARD_INT_TO_STRING_MAP[nums[l]].c_str()); isFlat = true; } } } } } if (!isFlat) cout << "NONE" << endl; } return 0; }