题解 | #24点运算#
24点运算
https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
bool cal(vector<double>a, int op[]) {
int j = 0;
for (int i = 0; i < 3; i++) {
if (op[i] == 1) {
a[i + 1] = a[i] + a[i + 1];
} else if (op[i] == 2) {
a[i + 1] = a[i] - a[i + 1];
} else if (op[i] == 3) {
a[i + 1] = a[i] * a[i + 1];
} else if (op[i] == 4) {
a[i + 1] = a[i] / a[i + 1];
}
}
if (a[3] == 24) {
return true;
} else {
return false;
}
}
int main() {
int op[4];
string card[13] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
int dic[13] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1};
// while (getline(cin, s)) {
// string ss[4], temp[4];
// ss[0] = s.substr(0, s.find(' '));
// temp[0] = s.substr(s.find(' ') + 1);
// ss[1] = temp[0].substr(0, temp[0].find(' '));
// temp[1] = temp[0].substr(temp[0].find(' ') + 1);
// ss[2] = temp[1].substr(0, temp[1].find(' '));
// temp[2] = temp[1].substr(temp[1].find(' ') + 1);
// ss[3] = temp[2].substr(0, temp[2].find(' '));
// }
vector<string>s(4);//vector数组一定要初始化长度大小。
cin >> s[0] >> s[1] >> s[2] >> s[3];
for (int i = 0; i < 4; i++) {
if (s[i] == "joker" || s[i] == "JOKER") {
cout << "ERROR";
return 0;
}
}
vector<double>a(4, 0);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
if (s[i] == card[j]) {
a[i] = dic[j];
}
}
}
sort(a.begin(), a.end());
bool flag = false;
do {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
for (int k = 1; k <= 4; k++) {
for (int z = 1; z <= 4; z++) { //用例中可以运算符可以重复
op[0] = i;
op[1] = j;
op[2] = k;
op[3] = z;
flag = cal(a, op);
if (flag == true) {
break;
}
}
if (flag == true) {
break;
}
}
if (flag == true) {
break;
}
}
if (flag == true) {
break;
}
}
if (flag == true) {
break;
}
} while (next_permutation(a.begin(), a.end()));
if (flag == true) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 13; j++) {
if (a[i] == dic[j]) {
s[i] = card[j];
}
}
}
char opp[4];
for (int i = 0; i < 3; i++) {
if (op[i] == 1) {
opp[i] = '+';
} else if (op[i] == 2) {
opp[i] = '-';
} else if (op[i] == 3) {
opp[i] = '*';
} else if (op[i] == 4) {
opp[i] = '/';
}
}
cout << s[0] << opp[0] << s[1] << opp[1] << s[2] << opp[2] << s[3];
} else {
cout << "NONE";
}
return 0;
}
// 64 位输出请用 printf("%lld")

