/*
This code runs for a long time mainly because the sum value needs to be re-calculated after each enumeration!
If it is faster, calculate the value of the front edge in the DFS, that is, the enumeration process, and know the final value. This eliminates the need to calculate the value from the beginning for each enumeration!
*/
1 # include <iostream> 2 # include <cstring> 3 # include <cstdio> 4 # include <algorithm> 5 using namespace STD; 6 7 char ch [20]; 8 char sign [3] = {'+ ','-','. '}; 9 int N, CNT; 10 int num [20]; 11 int signnum [1, 200]; 12 13 void DFS (int u) {14 if (u = N) {15 if (signnum ['+'] = n-1 | signnum ['+'] + signnum ['. '] = n-1 | signnum ['. '] = n-1 | signnum ['-'] = N-1) return; 16 for (INT I = 1; I <n; ++ I) {17 num [I] = I; 18 if (CH [I] = '. '){ 19 int S = I, V = I; 20 while (I <n & Ch [I] = '. ') {21 if (I + 1> 9) 22 s = S * 100 + (++ I); 23 else S = S * 10 + (++ I ); 24} 25 if (S> 10000) return; // you have to add this sentence .... then we were lucky! 26 num [v] = s; 27 -- I; 28} 29} 30 num [N] = N; 31 int S = num [1]; 32 For (INT I = 1; I <n; ++ I) 33 If (CH [I]! = '. ') {34 if (CH [I] =' + ') S + = num [I + 1]; 35 else S-= num [I + 1]; 36} 37 If (S = 0) {38 + + CNT; 39 if (CNT <= 20) {40 for (INT I = 1; I <N; ++ I) 41 printf ("% d % C", I, CH [I]); 42 printf ("% d \ n", N ); 43} 44} 45 return; 46} 47 for (INT I = 0; I <3; ++ I) {48 ch [u] = sign [I]; 49 + + signnum [sign [I]; 50 DFS (U + 1); 51 -- signnum [sign [I]; 52} 53} 54 55 int main () {56 while (scanf ("% d", & N )! = EOF) {57 CNT = 0; 58 DFS (1); 59 printf ("% d \ n", CNT); 60} 61 Return 0; 62}
Poj 1950 dessert (DFS enumeration)