【题目链接】:​​http://acm.hdu.edu.cn/showproblem.php?pid=1427​

【题目描述】:

速算24点


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5213    Accepted Submission(s): 1343


Problem Description

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

 

Input

每组输入数据占一行,给定四张牌。

 

Output

每一组输入数据对应一行输出。如果有解则输出"Yes",无解则输出"No"。

 

Sample Input

A 2 3 6 3 3 8 8

 

Sample Output

Yes No

 

Author

LL

 【思路】:DFS

【代码】:

/*****************************
[HDU 1427 速算24点]
Author:herongwei
Time:2017/6/4 16:25
language:C++
******************************/
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 1e6+10;
const int maxm = 55;
const int POINT=24;
const LL MOD = 999999997;
inline LL read(){
int c=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){c=c*10+ch-'0';ch=getchar();}
return c*f;
}
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int t,n,m,k,tp,ret,ans,ok;
char p1[3],p2[3],p3[3],p4[3];
int s1,s2,s3,s4;
int a[maxn],b[maxn],c[maxn],vis[maxn],sum[maxn],num[4];
int alpha_to_num(char p)
{
if(p=='A') return 1;
if(p=='J') return 11;
if(p=='Q') return 12;
if(p=='K') return 13;
}
void dfs(int sum,int cur,int step)
{
if(ok) return;
if(step==3){
if(sum-cur==POINT||sum+cur==POINT||sum*cur==POINT) ok=1;
if(cur&&sum%cur==0&&sum/cur==POINT) ok=1;
return;
}
dfs(sum+cur,num[step+1],step+1);
dfs(sum-cur,num[step+1],step+1);
dfs(sum*cur,num[step+1],step+1);
if(cur&&sum%cur==0) dfs(sum/cur,num[step+1],step+1);
dfs(sum,cur+num[step+1],step+1);
dfs(sum,cur-num[step+1],step+1);
dfs(sum,cur*num[step+1],step+1);
if(num[step+1]&&cur%num[step+1]==0) dfs(sum,cur/num[step+1],step+1);
}
int main()
{
freopen("in.txt","r",stdin);
while(~scanf("%s %s %s %s",p1,p2,p3,p4))
{
if(strlen(p1)==2) s1=10; else {if(isalpha(p1[0])) s1=alpha_to_num(p1[0]);else s1=p1[0]-'0';}
if(strlen(p2)==2) s2=10; else {if(isalpha(p2[0])) s2=alpha_to_num(p2[0]);else s2=p2[0]-'0';}
if(strlen(p3)==2) s3=10; else {if(isalpha(p3[0])) s3=alpha_to_num(p3[0]);else s3=p3[0]-'0';}
if(strlen(p4)==2) s4=10; else {if(isalpha(p4[0])) s4=alpha_to_num(p4[0]);else s4=p4[0]-'0';}
num[0]=s1;num[1]=s2;num[2]=s3;num[3]=s4;
ok=0;
sort(num,num+4);
do{
dfs(num[0],num[1],1);
}while(next_permutation(num,num+4)&&!ok);
if(ok)puts("Yes");
else puts("No");
}
return 0;
}