题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37
/*
思路:
1. 把数据读到 vector<double>数组中
2. 对数据进行排序
3. do while 循环
4. 对数据进行全排列 next_permutation(v.begin(), v.end())
5. 三层for循环 遍历所有的 操作符
*/
#include <algorithm>
#include<iostream>
#include <vector>
using namespace std;
vector<char> op{'+', '-', '*', '/'};
double cal(double a, double b, char ch){
switch (ch) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
int main(){
vector<double> v(4);
cin >> v[0] >> v[1] >> v[2] >> v[3];
sort(v.begin(), v.end());
do{
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 4; ++j){
for(int k = 0; k < 4; ++k){
double tmp = 0;
tmp = cal(v[0], v[1], op[i]);
tmp = cal(tmp, v[2], op[j]);
tmp = cal(tmp, v[3], op[k]);
if(tmp == 24){
cout << "true" << endl;
return 0;
}
}
}
}
}while(next_permutation(v.begin(), v.end()));
cout << "false" << endl;
return 0;
}
查看10道真题和解析
小天才公司福利 1279人发布