Problem Description
I believe that the vast majority of people have played shorthand at 24:00. Four cards are randomly given to you, including A(1),2,3,4,5,6,7,8,9,10,J(11),Q(12),K(13). Only '+', '-', '*', '/' operators and brackets are required to change the operation order so that the final operation result is 24 (each number must and can only be used once). The game is very simple, but it's often depressing when there's no solution. Your task is to judge whether there is a solution for each group of randomly generated four cards. In addition, we have stipulated that no decimal can appear in the whole calculation process.
Input
Each group of input data takes up one line, given four cards.
Output
Each set of input data corresponds to one line of output. Output "Yes" if there is a solution, and "No" if there is No solution.
Sample Input
A 2 3 6
3 3 8 8
Sample Output
Yes
No
Previous searches were all map problems, which surprised me!
In fact, it's just the enumeration of fried chicken violence. It's to be noted that the order of subtraction and division cannot be reversed, and that the divisor cannot be 0.
#include <iostream> #include <cstring> using namespace std; double num[4]; int dfs(int n){ for(int i=0;i<4;i++)//Because decimals cannot appear if(num[i]!=(int)num[i]) return 0; if(n==1){ //if(fabs(num[0]-24)<0.00001) if(num[0]==24) return 1; else return 0; } for(int i=0;i<n;i++) for(int j=i+1;j<n;j++){//Select any two numbers to be + - * / subtracted and divided double a=num[i],b=num[j]; num[j]=num[n-1];// //Subscript 0, 1 operation to 0 1 to 2 //The next round continues until the head is the result on num[0] //Enumeration to the 6th power of 4 num[i]=a+b; if(dfs(n-1)) return 1; num[i]=a*b; if(dfs(n-1)) return 1; num[i]=a-b; if(dfs(n-1)) return 1; num[i]=b-a; if(dfs(n-1)) return 1; //be careful!!! Divisor cannot be 0!!! if(b){ num[i]=a/b; if(dfs(n-1)) return 1; } if(a){ num[i]=b/a; if(dfs(n-1)) return 1; } num[i]=a; num[j]=b;//Numerical restoration } return 0; } int main(){ char mmp[4][3]; char a[14][3]={"0","A","2","3","4","5","6","7","8","9","10","J","Q","K"}; while(scanf("%s%s%s%s",mmp[0],mmp[1],mmp[2],mmp[3])!=EOF){ for(int i=0;i<4;i++){//To convert a card into a corresponding number. for(int j=1;j<=13;j++) if(strcmp(mmp[i],a[j])==0){ num[i]=j;//The corresponding number is wonderful! break; } //printf("%lf ",num[i]); } if(dfs(4)) printf("Yes\n"); else printf("No\n"); memset(mmp,0,sizeof(mmp)); memset(num,0,sizeof(num)); } return 0; }