#include <iostream> using namespace std; int n, m, k; int* aa; int* numm; int* fig; bool* used; bool search(int dep); bool found(); void out(); int main() { while (true) { cin >> n >> m; aa = new int[n]; numm = new int[n]; fig = new int[n]; used = new bool[n]; for (int i = 0; i < n; i++) { cin >> aa[i]; used[i] = false; } for (k = 0; k < n; k++) { if (search(0)) { cout << k << endl; out(); return 0; } } cout << "No Solution!" << endl; } return 0; } bool search(int dep) { if (dep > k) { return found(); } for (int i = 0; i < n; i++) { if (!used[i]) { numm[dep] = aa[i]; used[i] = true; for (int j = 0; j < 4; j++) { fig[dep] = j; if (search(dep + 1)) return true; } used[i] = false; } } return false; } bool found() { int x = numm[0]; for (int i = 0; i < k; i++) { switch (fig[i]) { case 0: x += numm[i + 1]; break; case 1: x -= numm[i + 1]; break; case 2: x = numm[i + 1]; break; case 3: x /= numm[i + 1]; break; } } return (x == m); } void out() { cout << numm[0]; for (int i = 0; i < k; i++) { switch (fig[i]) { case 0: cout << "+" << numm[i + 1]; break; case 1: cout << "-" << numm[i + 1]; break; case 2: cout << "" << numm[i + 1]; break; case 3: cout << "/" << numm[i + 1]; break; } } }将代码变量名更换
时间: 2024-04-04 15:35:19 浏览: 52
#include <iostream>
using namespace std;
int n, m, k;
int* nums;
int* ops;
int* order;
bool* used;
bool search(int dep);
bool found();
void output();
int main() {
while (true) {
cin >> n >> m;
nums = new int[n];
ops = new int[n];
order = new int[n];
used = new bool[n];
for (int i = 0; i < n; i++) {
cin >> nums[i];
used[i] = false;
}
for (k = 0; k < n; k++) {
if (search(0)) {
cout << k << endl;
output();
return 0;
}
}
cout << "No Solution!" << endl;
}
return 0;
}
bool search(int dep) {
if (dep > k) {
return found();
}
for (int i = 0; i < n; i++) {
if (!used[i]) {
order[dep] = i;
used[i] = true;
for (int j = 0; j < 4; j++) {
ops[dep] = j;
if (search(dep + 1)) return true;
}
used[i] = false;
}
}
return false;
}
bool found() {
int x = nums[order[0]];
for (int i = 0; i < k; i++) {
switch (ops[i]) {
case 0: x += nums[order[i + 1]]; break;
case 1: x -= nums[order[i + 1]]; break;
case 2: x = nums[order[i + 1]]; break;
case 3: x /= nums[order[i + 1]]; break;
}
}
return (x == m);
}
void output() {
cout << nums[order[0]];
for (int i = 0; i < k; i++) {
switch (ops[i]) {
case 0: cout << "+" << nums[order[i + 1]]; break;
case 1: cout << "-" << nums[order[i + 1]]; break;
case 2: cout << "" << nums[order[i + 1]]; break;
case 3: cout << "/" << nums[order[i + 1]]; break;
}
}
}
阅读全文