Files
python/TangDou/XiTi/1307.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

53 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
#define str to_string //利用define缩短代码
vector<string> path;
const int N = 30;
int a[N];
void dfs(int step, int res) {
if (step == 4) {
if (res == 24) {
for (int i = 0; i < path.size(); i++, puts("")) printf("%d", path[i]);
exit(0);
}
return;
}
int x = a[step];
if (x > res) swap(x, res);
path.push_back(str(res) + "+" + str(x) + "=" + str(res + x));
dfs(step + 1, res + x);
path.pop_back();
path.push_back(str(res) + "-" + str(x) + "=" + str(res - x));
dfs(step + 1, res - x);
path.pop_back();
path.push_back(str(res) + "*" + str(x) + "=" + str(res * x));
dfs(step + 1, res * x);
path.pop_back();
if (x && res % x == 0) {
path.push_back(str(res) + "/" + str(x) + "=" + str(res / x));
dfs(step + 1, res / x);
path.pop_back();
}
}
int main() {
for (int i = 0; i < 4; i++) scanf("%d", &a[i]);
do {
dfs(1, a[0]);
} while (next_permutation(a, a + 4));
puts("No answer!");
return 0;
}
/*
考虑添加括号的情况,假设**?**为运算符,一共只有5种:
1.((a?b)?c)?d
2.(a?(b?c))?d
3.a?((b?c)?d)
4.(a?b)?(c?d)
5.a?(b?(c?d))
*/