题目地址:
题目描述:
Problem I
23 Out of 5
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
Your task is to write a program that can decide whether you can find an arithmetic expression consisting of five given numbers (1<=i<=5) that will yield the value 23.
For this problem we will only consider arithmetic expressions of the following from:
where : {1,2,3,4,5} -> {1,2,3,4,5} is a bijective function
and {+,-,*} (1<=i<=4)
Input
The Input consists of 5-Tupels of positive Integers, each between 1 and 50.
Input is terminated by a line containing five zero's. This line should not be processed.
Output
For each 5-Tupel print "Possible" (without quotes) if their exists an arithmetic expression (as described above) that yields 23. Otherwise print "Impossible".
Sample Input
1 1 1 1 1
1 2 3 4 5
2 3 5 7 11
0 0 0 0 0
Sample Output
Impossible
Possible
Possible
题意:添加符号和数字 使等式成立。
题解:暴力搜索
代码:
/*
23 Out of 5 uva 10344
please read the problem clearly,
PI {1,2,3,4,5} -> {1,2,3,4,5} is a bijective function
we also should be familiar with the non-recursive structure,the Kye is the backtrack's value and status should rollback
if you want the all permutation int the next_permutation() you must set the array[] int the first sort in the start
*/
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string>
#include<algorithm>
using namespace std;
int A[5+5]={0};
int signal=0;//0->+ 1->- 2->*
/*caculate the number*/
int Calc(int a,int b,int c)
{
int Sum=0;
switch(c)
{
case 0:
Sum=a+b;
break;
case 1:
Sum=a-b;
break;
default:
Sum=a*b;
break;
}
return(Sum);
}
/*code blocks*/
int Blocks(int A[])
{
int a0=0,a1=0,a2=0,a3=0;
int Sum=0;
for(a0=0;a0<=2;a0++)
{
Sum=Calc(A[0],A[1],a0);//Sum should rollback the value before the Calc,this is not recursive,we should make a obvious rollback operation
for(a1=0;a1<=2;a1++)
{
int Tmp1=Sum;
Sum=Calc(Tmp1,A[2],a1);
for(a2=0;a2<=2;a2++)
{
int Tmp2=Sum;
Sum=Calc(Tmp2,A[3],a2);
for(a3=0;a3<=2;a3++)
{
int Tmp3=Sum;
Sum=Calc(Tmp3,A[4],a3);
//printf("***%d***\n",Sum);
if(Sum==23)
{
return(1);//possible
}
Sum=Tmp3;
}
Sum=Tmp2;
}
Sum=Tmp1;
}
}
return(0);
}
/*code block*/
int Blocks1()
{
int flag=0;
int B[5]={0};
int i0,i1,i2,i3,i4;
for(i0=0;i0<=5-1;i0++)
{
B[0]=A[i0];
for(i1=0;i1<=5-1;i1++)
{
B[1]=A[i1];
for(i2=0;i2<=5-1;i2++)
{
B[2]=A[i2];
for(i3=0;i3<=5-1;i3++)
{
B[3]=A[i3];
for(i4=0;i4<=5-1;i4++)
{
B[4]=A[i4];
//caculate the expression
{
flag=Blocks(B);
if(flag)
{
return(1);
}
}
}
}
}
}
}
return(0);
}
/*for test*/
int test()
{
return(0);
}
/*main process*/
int MainProc()
{
while(scanf("%d%d%d%d%d",&A[0],&A[1],&A[2],&A[3],&A[4])!=EOF&&(A[0]+A[1]+A[2]+A[3]+A[4])>0)
{
sort(A,A+5);
int flag=0;
//flag=Blocks1();
do
{
if(A[0]==2&&A[1]==3)//why not have this path in the permutation
{
A[0]=2;
}
flag=Blocks(A);
if(flag)
{
break;
}
}while(next_permutation(A,A+5));
if(!flag)
{
printf("Impossible\n");
}
else
{
printf("Possible\n");
}
}
return(0);
}
int main()
{
MainProc();
return(0);
}