Question: uva10400-game show math (backtracking + pruning)
N numbers are given, and a target value is given. The above numbers (all) must be used, and the sequence cannot be disordered. Then, +-*/is used to perform these operations, ask if you can get the target value. Note that the given number is between [-,] and can only be used when division is required. The intermediate calculation result cannot exceed the range. This operation cannot be performed if it is exceeded.
Solution: backtracing and pruning are used to save the computing results of each layer. If the present value of each layer appears, and the previous calculation finds that the target value is not obtained in the future, then you can directly cut it out.
The question was not clearly read, and the result was wa many times.
Code:
# Include <stdio. h> # include <string. h> # include <stdlib. h> const int n = 105; const int M = 70000; const int maxn = 32000; char op [N]; int num [N]; int N; int target; int flag; char op [4] = {'*', '-', '+', '/'}; int vis [N] [m]; void DFS (int K, int sum) {If (k = n-1) {/* For (INT I = 0; I <n-1; I ++) printf ("% C", op [I]); printf ("\ n"); printf ("% d \ n", sum ); */If (sum = target) Flag = 1; return;} int temp; For (int I = 0; I <4; I ++) {op [k] = op [I]; Switch (OP [I]) {Case '+ ': temp = sum + num [k + 1]; If (ABS (temp)> maxn) break; If (vis [k] [temp + maxn]) break; DFS (k + 1, temp); break; Case '-': temp = sum-num [k + 1]; If (ABS (temp)> maxn) break; if (vis [k] [temp + maxn]) break; DFS (k + 1, temp); break; Case '/': if (sum % num [k + 1] = 0) {temp = sum/num [k + 1]; If (ABS (temp)> maxn) break; if (vis [K] [temp + maxn]) break; DFS (k + 1, temp);} break; Case '*': temp = sum * num [k + 1]; if (ABS (temp)> maxn) break; If (vis [k] [temp + maxn]) break; DFS (k + 1, temp); break ;} if (FLAG) return; else if (ABS (temp) <= maxn &&! Vis [k] [temp + maxn]) vis [k] [temp + maxn] = 1 ;}} int main () {int t; scanf ("% d ", & T); While (t --) {scanf ("% d", & N); For (INT I = 0; I <n; I ++) scanf ("% d", & num [I]); scanf ("% d", & target); flag = 0; memset (VIS, 0, sizeof (VIS); DFS (0, num [0]); // printf ("% d \ n", flag); If (! Flag) printf ("no expression \ n"); else {for (INT I = 0; I <n; I ++) {if (I = n-1) printf ("% d = % d \ n", num [I], target); elseprintf ("% d % C", num [I], OP [I]) ;}} return 0 ;}