Counting
Accept:100 | Submit:807 |
Time Limit:2000MS | Memory Limit:65536KB |
Description
We are familiar with the game called “Counting 24”. Now it comes a problem that we want to know whether we can figure out the exact answer with given 4 numbers only using +,-,*,/ and (,).
Input
There are several cases in a test. Each case contains only 5 integers, a1, a2, a3, a4 and required answer. All integers are positive and no more than 100.
Output
If it is possible to figure out the required answer, output “Possible”; otherwise output “Impossible”.
Sample Input
5 5 1 5 24
Sample Output
Impossible
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<set>
using namespace std;
int a[4],ans;
set<int>s[16];
set<int>::iterator it1,it2;
inline void deal(int x,int tmp){s[x].insert(tmp);}
void cal(int x){
if(!s[x].empty())return;
for(int i=1;i<16;i++)
if((x&i)==i)
for(it1=s[i].begin();it1!=s[i].end();it1++)
for(it2=s[x-i].begin();it2!=s[x-i].end();it2++){
deal(x,(*it1)+(*it2));
deal(x,(*it1)*(*it2));
deal(x,(*it1)-(*it2));
if((*it2)&&(*it1)%(*it2)==0)deal(x,(*it1)/(*it2));
}
}
bool can(){
int i;
for(i=0;i<16;i++)
s[i].clear();
for(i=0;i<4;i++)
s[1<<i].insert(a[i]);
for(i=1;i<16;i++)
cal(i);
return s[15].find(ans)==s[15].end()?false:true;
}
int main(){
while(~scanf("%d%d%d%d%d",&a[0],&a[1],&a[2],&a[3],&ans))
printf("%s\n",can()?"Possible":"Impossible");
return 0;
}