开始用的回溯TLE了,后来改用全排列+DFS AC。
代码如下:
(0.728s):
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
int a[5], flag;
void solve(int cur, int sum)
{
if(cur == 5)
{
if(sum == 23)
flag = 1;
return ;
}
solve(cur + 1, sum + a[cur]);
if(flag)
return;
solve(cur + 1, sum - a[cur]);
if(flag)
return;
solve(cur + 1, sum * a[cur]);
if(flag)
return;
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
int b[5], s[5];
while(1)
{
for(int i = 0; i < 5; i++)
scanf("%d", &b[i]);
if(!b[0])
break;
for(int i = 0; i < 5; i++)
s[i] = i;
flag = 0;
do
{
for(int i = 0; i < 5; i++)
a[s[i]] = b[i];
solve(1, a[0]);
if(flag)
break;
}
while(next_permutation(s, s + 5));
if(flag)
printf("Possible\n");
else
printf("Impossible\n");
}
return 0;
}
排序之后再处理会更简单,优化(0.432s):
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
int a[5], flag;
void solve(int cur, int sum)
{
if(cur == 5)
{
if(sum == 23)
flag = 1;
return ;
}
solve(cur + 1, sum + a[cur]);
if(flag)
return;
solve(cur + 1, sum - a[cur]);
if(flag)
return;
solve(cur + 1, sum * a[cur]);
if(flag)
return;
}
int main()
{
#ifdef test
freopen("sample.txt", "r", stdin);
#endif
while(1)
{
for(int i = 0; i < 5; i++)
scanf("%d", &a[i]);
if(!a[0])
break;
flag = 0;
sort(a, a + 5); // 排一下序
do
{
solve(1, a[0]);
if(flag)
break;
}
while(next_permutation(a, a + 5));
if(flag)
printf("Possible\n");
else
printf("Impossible\n");
}
return 0;
}