速算24点
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2927 Accepted Submission(s): 699
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
Source
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#define INF 10000000
using namespace std;
int cnt = 0;
int flag = 0;
int b[4];
bool vis[4];
int a[4];
int n01[5],n12[5],n23[5];
int get(int n1,int op,int n2)
{
switch(op)
{
case 0: return n1 + n2;
case 1: return n1 - n2;
case 2: return n1 * n2;
case 3:
if(n2==0||(n1%n2) ) return INF;//除数需要处理一下不能整除,除数为0
return n1 / n2;
}
}
int dfs()
{ int n2,n3,i,j,k;
for(i=0;i<4;i++){ ((a@b) @c) @d
n01[i] = get(a[0],i,a[1]);
if(n01[i]==INF)continue;
for(j=0;j<4;j++){
n2 = get(n01[i],j,a[2]);
if(n2==INF)continue;
for(k=0;k<4;k++){
n3 = get(n2,k,a[3]);
if(n3==INF)continue;
if(n3 == 24) return 1;
}
}
}
for(i=0;i<4;i++){// (a@b)@(c@d)
if(n01[i]==INF)continue;
for(j=0;j<4;j++){
n23[j] = get(a[2],j,a[3]);//n01 n23
if(n23[j]==INF) continue;
for(k=0;k<4;k++){
n3 = get(n01[i],k,n23[j]);
if(n3==INF)continue;
if(n3 == 24) return 1;
}
}
}
for(i=0;i<4;i++){// a @ ((b@c)@d)
n12[i] = get(a[1],i,a[2]);
if(n12[i]==INF)continue;
for(j=0;j<4;j++){
n2 = get(n12[i],j,a[3]);
if(n2==INF)continue;
for(k=0;k<4;k++){
n3 = get(a[0],k,n2);
if(n3 == 24) return 1;
if(n3==INF)continue;
}
}
}
for(i=0;i<4;i++){ // a @ ( b@(c@d) )
if(n23[i]==INF)continue;
for(j=0;j<4;j++){
n2 = get(a[1],j,n23[i]);
if(n2==INF)continue;
for(k=0;k<4;k++){
n3 = get(a[0],k,n2);
if(n3 == 24) return 1;
if(n3==INF)continue;
}
}
}
for(i=0;i<4;i++){// (a @ (b@c))@d
if(n12[i]==INF)continue;
for(j=0;j<4;j++){
n2 = get(a[0],j,n12[i]);
if(n2==INF)continue;
for(k=0;k<4;k++){
n3 = get(n2,k,a[3]);
if(n3 == 24) return 1;
if(n3==INF)continue;
}
}
}
return 0;
}
void dfs1(int x)
{
if(x==4){
if(dfs()){
flag=1;
return ;
}
}
for(int i=0;i<4;i++){
if(!vis[i]){
vis[i] = 1;
a[x] = b[i];
dfs1(x+1);
if(flag)return ;
vis[i] = 0;
}
}
}
int main()
{
int n;
char s[3];
while(1)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(s,0,sizeof(s));
for(int i=0;i<4;i++){
if(scanf("%s",s)==EOF)return 0;
if(s[0]=='A') b[i] = 1;
else if(s[0]=='J') b[i] = 11;
else if(s[0]=='Q') b[i] = 12;
else if(s[0]=='K') b[i] = 13;
else if(s[0]=='1') b[i] = 10;
else b[i] = s[0] - '0';
}//printf("%d %d %d %d\n",b[0],b[1],b[2],b[3]);
flag = 0;
memset(vis,0,sizeof(vis));
dfs1(0);
printf("%s\n",flag?"Yes":"No");
}
return 0;
}