Problem Solving Ideas:
Enumerates all the possible scenarios.
First of all, four numbers are all arranged, for each arrangement, through the DFS simulation with the case of different brackets, for each case, then the subtraction operation, see if there is a situation can be calculated 24 results.
Here are 2 more questions:
1 to convert the input, especially a, 10, J, Q, K, such as special cards.
2 before the division operation to be judged, the first divisor can not be 0, or the program will crash, and then to be divisible.
Code:
1#include <cstdio>2#include <iostream>3#include <string.h>4#include <algorithm>5 using namespacestd;6 intK;7 intcard[4];8 Chartemp[4];9 //handle a few special cards.Ten voidTrainti) One { A if(strcmp (temp,"A")==0) card[i]=1; - Else if(strcmp (temp,"Ten")==0) card[i]=Ten; - Else if(strcmp (temp,"J")==0) card[i]= One; the Else if(strcmp (temp,"Q")==0) card[i]= A; - Else if(strcmp (temp,"K")==0) card[i]= -; - ElseCard[i] = (int) (temp[0]- -); - } + intJudge24 (intN) - { + return(n = = -); A } at voidDfsintSumintCurintm) - { - if(k = =1)return; - if(M = =3) - { - if(Judge24 (sum+cur) | | judge24 (sum-cur) | | Judge24 (sum*cur)) in { - //printf ("%d%d\n", sum,cur); toK =1; + } - Else if(cur!=0&& sum%cur==0&& Judge24 (sum/cur ))) the{//Note that the divisor cannot be 0 and must be divisible * //printf ("%d%d\n", sum,cur); $k=1;Panax Notoginseng } - return; the } + //Use this search to vary the order of operations by using virtual parentheses ADFS (Sum+cur, card[m+1], m+1); theDFS (Sum-cur, card[m+1], m+1); +DFS (Sum*cur, card[m+1], m+1); - if(cur!=0&& sum%cur==0) Dfs (Sum/cur, card[m+1], m+1); $ $DFS (SUM, cur+card[m+1], m+1); -DFS (SUM, cur-card[m+1], m+1); -DFS (SUM, cur*card[m+1], m+1); the if(card[m+1]!=0&& cur%card[m+1]==0) DFS (SUM, cur/card[m+1], m+1); - }Wuyi intMainvoid) the { - //freopen ("1427.in", "R", stdin); Wu while(SCANF ("%s", temp)! =EOF) - { AboutK =0; $Tra0); - for(intI=1; i<4; i++) - { -scanf"%s", temp); ATRA (i);//for converting characters to numbers + } theSort (Card, card+4);//to sort before you can arrange them all - Do $ { theDFS (card[0], card[1],1);//for each arrangement, DFS is constructed to construct a different sequence of operations the} while(Next_permutation (Card, card+4) && k==0);//construct different formulas by arranging them all the if(k = =0) printf ("no\n"); the Elseprintf"yes\n"); - } in return 0; the}//2015-07-25
HDU1427 Calculator 24 points