题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
string res_str;
map<string, int> umap = {
{"2", 2},
{"3", 3},
{"4", 4},
{"5", 5},
{"6", 6},
{"7", 7},
{"8", 8},
{"9", 9},
{"10", 10},
{"J", 11},
{"Q", 12},
{"K", 13},
{"A", 1},
};
bool bp(vector<string>& vec, vector<bool>& used, int result, int count,
string path) {
if (count == 4 && result == 24) {
res_str = path;
return true;
}
for (int i = 0; i < 4; i++) {
if (used[i])
continue;
used[i] = true;
if (count == 0) {
if (bp(vec, used, result + umap[vec[i]], count + 1,
path + '+' + vec[i]))
return true;
} else if (bp(vec, used, result + umap[vec[i]], count + 1,
path + '+' + vec[i])
|| bp(vec, used, result - umap[vec[i]], count + 1,
path + '-' + vec[i])
|| bp(vec, used, result * umap[vec[i]], count + 1,
path + '*' + vec[i])
|| bp(vec, used, result / umap[vec[i]], count + 1,
path + '/' + vec[i]))
return true;
used[i] = false;
}
return false;
}
int main() {
string input;
vector<string> vec;
int index = 0;
while (cin >> input) {
if (input.size() > 1) {
cout << "ERROR";
index = 1;
break;
}
if (input == "A" || input == "K" || input == "Q" || input == "J" || isdigit(input[0]))
vec.push_back(input);
else {
cout << "ERROR";
index = 1;
break;
}
}
if (index == 0) {
vector<bool> used(4, false);
if (bp(vec, used, 0, 0, "")) {
cout << res_str.substr(1);
} else {
cout << "NONE";
}
}
}
// 64 位输出请用 printf("%lld")
