Question connection: answer questions
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1427
Train of Thought: simple DFS, DFS (sum, next, p) indicates that the calculated value is sum, the calculated value in parentheses is next, and the currently used card subscript is P, in fact, we divide the two values out of and in brackets into sum and next for processing.
Intuition tells us that the four numbers only need one layer of parentheses to participate in the operation, and there is no need to use multiple parentheses to change the operation sequence. Therefore, the above DFS idea is correct.
There are two solutions for the next card:
1. Calculate next into sum, And the next card is the calculated value in the new brackets.
2. Calculate the value of the next card into next, and add the next card to brackets.
For the preceding two processing methods, each method is further divided into four situations: addition, subtraction, multiplication, and division. For Division, special processing is required. The divisor cannot be 0, in addition, decimals are not allowed during the operation. Therefore, you must check before performing Division operations.
# Include <iostream> # include <stdio. h> # include <stdlib. h> # include <string. h ># include <string >#include <algorithm> using namespace STD; int cardnum [10]; // cardnum [I] = digit size of card I bool flag = false; // flag = true indicates that the 24-point int getnum (string s) can be calculated) // poker card number s turn to number {If (s [0]> = '2' & S [0] <= '9 ') return s [0]-'0'; If (S = "10") return 10; Switch (s [0]) {Case 'A': return 1; case 'J': Return 11; Case 'q': Return 12; Case 'K': return 1 3 ;}} void DFS (INT sum, int next, int p) // indicates that the calculated value is sum and the calculated value in parentheses is next, the subscript of the currently used card is P {If (P = 4) // 4th cards are being used {If (sum + next = 24 | sum-Next = 24 | sum * Next = 24) Flag = true; if (next! = 0 & sum % Next = 0 & sum/next = 24) Flag = true; return;} // 1. Do not enclose DFS (sum + next, cardnum [p + 1], p + 1); DFS (Sum-Next, cardnum [p + 1], p + 1); DFS (sum * next, cardnum [p + 1], p + 1); If (next! = 0 & sum % Next = 0) DFS (sum/next, cardnum [p + 1], p + 1); // 2, Parentheses, you need to change the Operation Sequence DFS (sum, next + cardnum [p + 1], p + 1); DFS (sum, next-cardnum [p + 1], P + 1); DFS (sum, next * cardnum [p + 1], p + 1); If (cardnum [p + 1]! = 0 & next % cardnum [p + 1] = 0) DFS (sum, next/cardnum [p + 1], p + 1);} int main () {string in; while (CIN> In) {flag = false; cardnum [1] = getnum (in); For (INT I = 2; I <= 4; I ++) {CIN> In; cardnum [I] = getnum (in);} Sort (cardnum + 1, cardnum + 5 ); do {DFS (cardnum [1], cardnum [2], 2);} while (! Flag & next_permutation (cardnum + 1, cardnum + 5); If (FLAG) printf ("Yes \ n"); else printf ("NO \ n ");} return 0 ;}
[HDU 1427] (DFS Brute Force Search)