1 条题解
-
0
由于数字数量固定(4个),运算符选择有限(3种),我们可以采用暴力枚举的方法:
-
枚举第一个运算符的3种可能
-
枚举第二个运算符的3种可能
-
枚举第三个运算符的3种可能
总共有 种组合。
对于每种组合,按照从左到右的顺序计算表达式值,检查是否等于 。
#include <bits/stdc++.h> using namespace std; const vector<char> OPS = {'+', '-', '*'}; void solve() { vector<int> nums(4); for (auto &v : nums) cin >> v; for (auto op1 : OPS) for (auto op2 : OPS) for (auto op3 : OPS) { vector<char> ops = {op1, op2, op3}; int ans = nums[0]; for (int i = 1; i < 4; i++) { if (ops[i - 1] == '+') ans += nums[i]; else if (ops[i - 1] == '-') ans -= nums[i]; else ans *= nums[i]; } if (ans == 24) { cout << nums[0] << op1 << nums[1] << op2 << nums[2] << op3 << nums[3] << endl; return; } } cout << -1 << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int t; cin >> t; while (t--) solve(); return 0; }
-
- 1
信息
- ID
- 2725
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- (无)
- 递交数
- 3
- 已通过
- 2
- 上传者