给你5个数字 要求你能随意使用 + - *三个运算符是这五个数的结果为23(每个数只能使用一次)
先排序,再用nenx_premutation函数枚举每一个全排列
对于每一个全排列 通过递归来暴力检查
<pre name="code" class="cpp">#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int con[5];
int temp = 0;
bool dfs(int cur,int temp){
if (cur == 5){
if (temp == 23)
return true;
else return false;
}
if (dfs(cur + 1, temp + con[cur])) return true;
if (dfs(cur + 1, temp * con[cur])) return true;
if (dfs(cur + 1, temp - con[cur])) return true;
return false;
}
bool cmp(int a,int b){
return a < b;
}
int main(){
while (true){
int x = 0;
for (int i = 0; i < 5; i++){
cin >> con[i];
x += con[i];
}
if (x == 0)
break;
bool flag = true;
sort(con,con+5,cmp);
for (int i = 0; i < 5; i++)
cout <<" "<< con[i];
cout << endl;
do{
if (dfs(1, temp)){
cout << "Possible" << endl;
flag = false;
break;
}
} while (next_permutation(con, con + 5));
if (flag)
cout << "Impossible" << endl;
}
return 0;
}