题解:P13678 [GCPC 2023] Mischievous Math
xiaolong6666 · · 题解
题目传送门
废话不少说,先简单概括题目,一句话就是:
我们要找一组三个数
既然了解了题目意思,一个小小的枚举即可解决问题。
我们分别枚举
- 只用一个数。
- 用两个数。
- 三个数全用。
随后比较结果(注意因为有除法的缘故要用 double),核心公式就是:
在代码中还有一点小小的优化,例如第一个三元组不符合要求就直接输出并退出。
AC code:
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
bool eq(double x, double y) {
return fabs(x - y) < EPS;
}
bool canMakeWithTwo(double x, double y, double target) {
if (eq(x + y, target)) return true;
if (eq(x - y, target)) return true;
if (eq(y - x, target)) return true;
if (eq(x * y, target)) return true;
if (fabs(y) > EPS && eq(x / y, target)) return true;
if (fabs(x) > EPS && eq(y / x, target)) return true;
return false;
}
bool canMake(vector<double> nums, double target) {
int n = nums.size();
if (n == 0) return false;
if (n == 1) {
if (eq(nums[0], target)) return true;
return false;
}
if (n == 2) {
return canMakeWithTwo(nums[0], nums[1], target);
}
sort(nums.begin(), nums.end());
do {
double a = nums[0], b = nums[1], c = nums[2];
vector<double> firstResults;
firstResults.push_back(a + b);
firstResults.push_back(a - b);
firstResults.push_back(b - a);
firstResults.push_back(a * b);
if (fabs(b) > EPS) firstResults.push_back(a / b);
if (fabs(a) > EPS) firstResults.push_back(b / a);
for (double r : firstResults) {
if (eq(r + c, target)) return true;
if (eq(r - c, target)) return true;
if (eq(c - r, target)) return true;
if (eq(r * c, target)) return true;
if (fabs(c) > EPS && eq(r / c, target)) return true;
if (fabs(r) > EPS && eq(c / r, target)) return true;
}
vector<double> secondResults;
secondResults.push_back(b + c);
secondResults.push_back(b - c);
secondResults.push_back(c - b);
secondResults.push_back(b * c);
if (fabs(c) > EPS) secondResults.push_back(b / c);
if (fabs(b) > EPS) secondResults.push_back(c / b);
for (double r : secondResults) {
if (eq(a + r, target)) return true;
if (eq(a - r, target)) return true;
if (eq(r - a, target)) return true;
if (eq(a * r, target)) return true;
if (fabs(r) > EPS && eq(a / r, target)) return true;
if (fabs(a) > EPS && eq(r / a, target)) return true;
}
} while (next_permutation(nums.begin(), nums.end()));
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int d;
if (!(cin >> d)) return 0;
for (int a = 1; a <= 100; ++a) {
if (a == d) continue;
for (int b = a + 1; b <= 100; ++b) {
if (b == d) continue;
for (int c = b + 1; c <= 100; ++c) {
if (c == d) continue;
bool possible = false;
if (eq(a, d) || eq(b, d) || eq(c, d)) possible = true;
if (!possible) {
if (canMakeWithTwo(a, b, d)) possible = true;
else if (canMakeWithTwo(a, c, d)) possible = true;
else if (canMakeWithTwo(b, c, d)) possible = true;
}
if (!possible) {
vector<double> nums = {double(a), double(b), double(c)};
if (canMake(nums, d)) possible = true;
}
if (!possible) {
cout << a << " " << b << " " << c << "\n";
return 0;
}
}
}
}
cout << "1 20 30\n";
return 0;
}