import java.util.Scanner; public class Main { private static int n,m,k; private static int[] aa,numm,fig; private static boolean[] used; public static void main(String[] args){ Scanner input = new Scanner(System.in); while (true){ n = input.nextInt(); m = input.nextInt(); aa = new int[n]; numm = new int[n]; fig = new int[n]; used = new boolean[n]; for(int i=0; i<n; i++){ aa[i] = input.nextInt(); used[i] = false; } for(k=0; k<n; k++){ if(search(0)){ System.out.println(k); out(); return; } } System.out.println("No Solution!"); } } private static boolean 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; } private static boolean found(){ int x = numm[0]; for(int i=0; i<k; i++){ switch (fig[i]) { case 0 -> x += numm[i + 1]; case 1 -> x -= numm[i + 1]; case 2 -> x = numm[i + 1]; case 3 -> x /= numm[i + 1]; } } return (x==m); } private static void out(){ System.out.print(numm[0]); for(int i=0; i<k; i++) switch (fig[i]) { case 0 -> { System.out.print("+" + numm[i + 1]); continue; } case 1 -> { System.out.print("-" + numm[i + 1]); continue; } case 2 -> { System.out.print("" + numm[i + 1]); continue; } case 3 -> { System.out.print("/" + numm[i + 1]); continue; } } } } 修改为c++语言
时间: 2024-03-20 22:40:42 浏览: 69
下面是修改后的 C++ 代码,注意修改了一些语法和变量类型:
```cpp
#include <iostream>
using namespace std;
int n, m, k;
int aa[20], numm[20], fig[20];
bool used[20];
bool search(int dep);
bool found();
void out();
int main() {
while (true) {
cin >> n >> m;
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;
}
}
cout << endl;
}
```
阅读全文