题目
传说,小圆搜题上有一个24点排位赛……
标程
#include <bits/stdc++.h>
const double EPS = 1e-6;
struct Ans{
double x, y;
int opt;
double res;
} ans[3];
double a[4];
int sgn(double x) {
if (x > EPS) return 1;
if (x < -EPS) return -1;
return 0;
}
char toChar(int opt) {
return opt == 0 ? '+' : opt == 1 ? '-' : opt == 2 ? '*' : '/';
}
void print() {
puts("-----------------------------------------");
for (int i = 0; i < 3; i++) {
printf("%.2lf %c %.2lf = %.2lf\n", ans[i].x, toChar(ans[i].opt), ans[i].y, ans[i].res);
}
puts("-----------------------------------------");
puts("");
}
double calc(double x, double y, int opt) {
switch (opt) {
case 0: return x + y;
case 1: return x - y;
case 2: return x * y;
case 3: return x / y;
}
}
bool die;
void dfs(int dep) {
if (die) return;
if (dep == 1) {
print();
die = true;
return;
}
double b[4];
memcpy(b, a, sizeof(b));
for (int i = 0; i < dep; i++) {
for (int j = 0; j < dep; j++) {
if (i == j) continue;
for (int k = 0; k < 4; k++) {
if (sgn(a[j]) == 0 && k == 3) continue;
double res = calc(a[i], a[j], k);
if (dep == 2 && sgn(res - 24)) continue;
ans[4-dep] = (Ans){a[i], a[j], k, res};
int ti = i, tj = j;
if (ti > tj) std::swap(ti, tj);
a[ti] = res;
if (tj < dep) std::swap(a[tj], a[dep-1]);
sort(a, a + dep - 1, std::greater<int>());
dfs(dep-1);
memcpy(a, b, sizeof(a));
}
}
}
}
void solve() {
sort(a, a + 4, std::greater<int>());
die = false;
dfs(4);
if (!die) {
puts("-----------------------------------------");
puts("No solution.");
puts("-----------------------------------------");
puts("");
}
}
int main() {
while (std::cin >> a[0] >> a[1] >> a[2] >> a[3]) {
solve();
}
return 0;
}
这是原创,不是转载……