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 08:40:18 浏览: 48
java代码-实训4-3 import java.util.Scanner
下面是将Java代码转换为C++代码的实现:
```c++
#include<bits/stdc++.h>
using namespace std;
int n,m,k;
int aa[100],numm[100],fig[100];
bool used[100];
bool search(int dep);
bool found();
void out();
int main()
{
while (scanf("%d%d",&n,&m)==2)
{
for(int i=0;i<n;i++)
{
scanf("%d",&aa[i]);
used[i]=false;
}
for(k=0;k<n;k++)
{
if(search(0))
{
printf("%d\n",k);
out();
printf("\n");
break;
}
}
if(k==n)
printf("No Solution!\n");
}
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()
{
printf("%d",numm[0]);
for(int i=0;i<k;i++)
{
switch(fig[i])
{
case 0:printf("+%d",numm[i+1]);break;
case 1:printf("-%d",numm[i+1]);break;
case 2:printf("%d",numm[i+1]);break;
case 3:printf("/%d",numm[i+1]);break;
}
}
}
```
阅读全文