简单DFS,主要(a@b)@(c@d)这种情况。即在DFS时体现先算前面一部分和先算后面一部分。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int num[4];
int flag;
void dfs(int sum,int cur,int deep)
{
if(flag) return;
if(deep==3)
{
if(sum+cur==24||sum-cur==24||sum*cur==24) flag=1;
if(cur!=0&&sum%cur==0&&sum/cur==24) flag=1;
return;
}
//先算前一部分
dfs(sum+cur,num[deep+1],deep+1);
dfs(sum-cur,num[deep+1],deep+1);
dfs(sum*cur,num[deep+1],deep+1);
if(cur!=0&&sum%cur==0) dfs(sum/cur,num[deep+1],deep+1);
//先算后一部分
dfs(sum,cur+num[deep+1],deep+1);
dfs(sum,cur-num[deep+1],deep+1);
dfs(sum,cur*num[deep+1],deep+1);
if(num[deep+1]!=0&&cur%num[deep+1]==0) dfs(sum,cur/num[deep+1],deep+1);
}
int main()
{
char s[4];
while(scanf("%s",s)!=EOF)
{
if(strlen(s)==2) num[0]=10;
else
{
if(s[0]=='A') num[0]=1;
else if(s[0]=='J') num[0]=11;
else if(s[0]=='Q') num[0]=12;
else if(s[0]=='K') num[0]=13;
else num[0]=s[0]-'0';
}
for(int i=1;i<=3;i++)
{
scanf("%s",s);
if(strlen(s)==2) num[i]=10;
else
{
if(s[0]=='A') num[i]=1;
else if(s[0]=='J') num[i]=11;
else if(s[0]=='Q') num[i]=12;
else if(s[0]=='K') num[i]=13;
else num[i]=s[0]-'0';
}
}
sort(num,num+4);
flag=0;
do
{
dfs(num[0],num[1],1);
}while(next_permutation(num,num+4)&&!flag);
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}