这个方法0.33(一遍全排列一遍求“23”)比上次那个0.15(用next_permutation生成全排序,在递归求“23”)慢一点
#include<stdio.h>
#include<string.h>
int arr[5];
bool used[5];
bool sum23(int cur,int sum)
{
if(cur == 5)
{
if(sum == 23)
return true;
else return false;
}
bool res = false;
for(int i = 0; i < 5; ++i)
{
if(!used[i])
{
used[i] = true;
res = res || sum23(cur+1,sum+arr[i]);
res = res || sum23(cur+1,sum-arr[i]);
res = res || sum23(cur+1,sum*arr[i]);
if(res)
return true;
used[i] = false;
}
}
return res;
}
int main()
{
freopen("input.txt","r",stdin);
freopen("out.txt","w",stdout);
while(scanf("%d%d%d%d%d",arr,arr+1,arr+2,arr+3,arr+4)==5)
{
if(!arr[0]&&!arr[1]&&!arr[2]&&!arr[3]&&!arr[4])
break;
bool ok = false;
memset(used,false,sizeof(used));
for(int i=0; i < 5; ++i)
{
used[i] = true;
if(sum23(1, arr[i]))
{
ok = true;
break;
}
used[i] = false;
}
if(ok)
{
printf("Possible\n");
}
else
{
printf("Impossible\n");
}
}
}