http://acm.hdu.edu.cn/showproblem.php?pid=1427
不传引用会TLE
#include <bits/stdc++.h> using namespace std; double epx = 1e-10; int cmp = 24; bool judge(vector<int> &nums) { if (nums.size() == 1) { if (nums[0] == cmp) return true; return false; } for (int i = 0; i < nums.size(); ++i) { for (int j = i + 1; j < nums.size(); ++j) { vector<int> t; for (int k = 0; k < nums.size(); ++k) { if (k != j && k != i) t.push_back(nums[k]); } int a = nums[i], b = nums[j]; t.push_back(a - b); if (judge(t)) return true; t.pop_back(); t.push_back(b - a); if (judge(t)) return true; t.pop_back(); t.push_back(b * a); if (judge(t)) return true; t.pop_back(); t.push_back(b + a); if (judge(t)) return true; t.pop_back(); if (a != 0 && b % a == 0) { t.push_back(b / a); if (judge(t)) return true; t.pop_back(); } if (b != 0 && a % b == 0) { t.push_back(a / b); if (judge(t)) return true; t.pop_back(); } } } return false; } char a[22][22]; int char2double(char ch) { if (ch == 'A') return 1; else if (ch == 'J') return 11; else if (ch == 'Q') return 12; else if (ch == 'K') return 13; else if (ch == '1') { return 10; } else return ch - '0'; } void work() { vector<int> vc; for (int i = 0; i < 4; ++i) { vc.push_back(char2double(a[i][0])); } if (judge(vc)) { printf("Yes "); } else printf("No "); } int main() { // freopen("data.txt", "r", stdin); while (scanf("%s%s%s%s", a[0], a[1], a[2], a[3]) > 0) work(); return 0; }
还有这题不是小数的,小数的话可以用eps简单模拟
#include <bits/stdc++.h> using namespace std; double epx = 1e-5; double cmp = 24.0; bool judge(vector<double>& nums) { if (nums.size() == 1) { if (fabs(cmp - nums[0]) < epx) return true; return false; } for (int i = 0; i < nums.size(); ++i) { for (int j = i + 1; j < nums.size(); ++j) { vector<double> t; for (int k = 0; k < nums.size(); ++k) { if (k != j && k != i) t.push_back(nums[k]); } double a = nums[i], b = nums[j]; t.push_back(a - b); if (judge(t)) return true; t.pop_back(); t.push_back(b - a); if (judge(t)) return true; t.pop_back(); t.push_back(b * a); if (judge(t)) return true; t.pop_back(); t.push_back(b + a); if (judge(t)) return true; t.pop_back(); if (fabs(a - 0) > 10 * epx) { t.push_back(b / a); if (judge(t)) return true; t.pop_back(); } if (fabs(b - 0) > 10 * epx) { t.push_back(a / b); if (judge(t)) return true; t.pop_back(); } } } return false; } void work() { double a, b, c, d; cin >> a >> b >> c >> d; vector<double> vc; vc.push_back(a); vc.push_back(b); vc.push_back(c); vc.push_back(d); if (judge(vc)) cout << "true" << endl; else cout << "false" << endl; } int main() { work(); return 0; }
https://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb
这题莫名奇妙wa