您的位置:首页 > 其它

hdu 1427 速算24点 dfs暴力搜索

2016-05-15 11:07 411 查看

速算24点

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)


[align=left]Problem Description[/align]
速算24点相信绝大多数人都玩过。就是随机给你四张牌,包括A(1),2,3,4,5,6,7,8,9,10,J(11),Q(12),K(13)。要求只用'+','-','*','/'运算符以及括号改变运算顺序,使得最终运算结果为24(每个数必须且仅能用一次)。游戏很简单,但遇到无解的情况往往让人很郁闷。你的任务就是针对每一组随机产生的四张牌,判断是否有解。我们另外规定,整个计算过程中都不能出现小数。

[align=left]Input[/align]
每组输入数据占一行,给定四张牌。

[align=left]Output[/align]
每一组输入数据对应一行输出。如果有解则输出"Yes",无解则输出"No"。

[align=left]Sample Input[/align]

A 2 3 6
3 3 8 8

[align=left]Sample Output[/align]

Yes
No

[align=left]Author[/align]
LL
思路:暴力搜索,利用next_permutation全排列

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define inf 999999999
#define esp 0.00000000001
//#pragma comment(linker, "/STACK:102400000,102400000")
int scan()
{
int res = 0 , ch ;
while( !( ( ch = getchar() ) >= '0' && ch <= '9' ) )
{
if( ch == EOF ) return 1 << 30 ;
}
res = ch - '0' ;
while( ( ch = getchar() ) >= '0' && ch <= '9' )
res = res * 10 + ( ch - '0' ) ;
return res ;
}
int a[5];
int ans;
int getnum(string a)
{
if(a[0]=='1')
return 10;
if(a[0]>='2'&&a[0]<='9')
return a[0]-'0';
if(a[0]=='A')
return 1;
if(a[0]=='J')
return 11;
if(a[0]=='K')
return 13;
if(a[0]=='Q')
return 12;
}
void dfs(int num,int gg,int step)
{
if(step==4)
{
if(num==24)
ans=1;
return;
}
//不加括号
dfs(num+gg,a[step+1],step+1);
dfs(num-gg,a[step+1],step+1);
dfs(num*gg,a[step+1],step+1);
if(gg!=0&&num%gg==0)
dfs(num/gg,a[step+1],step+1);
//加括号
if(step!=3)
{
dfs(num,gg+a[step+1],step+1);
dfs(num,gg*a[step+1],step+1);
dfs(num,gg-a[step+1],step+1);
if(a[step+1]!=0&&gg%a[step+1]==0)
dfs(num,gg/a[step+1],step+1);
}
}
string ch[10];
int main()
{
int x,y,z,i,t;
while(cin>>ch[0]>>ch[1]>>ch[2]>>ch[3])
{
ans=0;
for(i=0;i<4;i++)
a[i]=getnum(ch[i]);
sort(a,a+4);
do
{
dfs(a[0],a[1],1);
}
while(next_permutation(a,a+4));
if(ans)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: