您的位置:首页 > 其它

23 Out of 5 uva+回溯

2014-06-04 22:29 351 查看
23Outof5
Input:standardinput
Output:standardoutput
TimeLimit:1second
MemoryLimit:32MB
Yourtaskistowriteaprogramthatcandecidewhetheryoucanfindanarithmeticexpressionconsistingoffivegivennumbers


(1<=i<=5)thatwillyieldthevalue23.

Forthisproblemwewillonlyconsiderarithmeticexpressionsofthefollowingfrom:



where

:{1,2,3,4,5}->{1,2,3,4,5}isabijectivefunction

and

{+,-,*}(1<=i<=4)

Input

TheInputconsistsof5-TupelsofpositiveIntegers,eachbetween1and50.

Inputisterminatedbyalinecontainingfivezero's.Thislineshouldnotbeprocessed.

Output

Foreach5-Tupelprint"Possible"(withoutquotes)iftheirexistsanarithmeticexpression(asdescribedabove)thatyields23.Otherwiseprint"Impossible".

SampleInput

11111

12345

235711

00000

SampleOutput

Impossible

Possible

Possible

解决方案:搞了半天,原来顺序可以换的。

#include<iostream>
#include<cstdio>
#include<cstring>
usingnamespacestd;
inta[5];
boolvis[5];
boolflag;
voiddfs(ints,intsum){
if(s==5){
if(sum==23)flag=true;
return;
}
for(inti=0;i<5;i++){
if(!vis[i]){
vis[i]=true;
if(s==0)
{dfs(s+1,a[i]);}
else{dfs(s+1,sum-a[i]);
dfs(s+1,sum*a[i]);
dfs(s+1,sum+a[i]);}
vis[i]=false;
}
}

}
intmain(){

while(~scanf("%d%d%d%d%d",&a[0],&a[1],&a[2],&a[3],&a[4])&&(a[0]+a[1]+a[2]+a[3]+a[4])){
flag=false;
memset(vis,false,sizeof(vis));
dfs(0,0);
if(flag)cout<<"Possible\n";
elsecout<<"Impossible\n";
}
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: