Classic pruning topics, annotated code for others. Or you have to knock yourself a lot. Reflection, Reflection!
1#include"iostream"2#include"algorithm"3#include"Memory.h"4 using namespacestd;5 6 intsticks[ -],n,len,num;7 BOOLused[ -];8 9 BOOLcmpintAintb)Ten { One returnA >b; A } - - BOOLDfsintCurintLeftintLevel ) the{//cur: The currently calculated stick number, left: the length of the segment remaining, level: the number of sticks that have been successful - if(left = =0) {//match a stick to succeed - if(Level = = num-2)return true; - for(cur =0; used[cur];cur++);//find the next length that has not been visited +Used[cur] =true; - if(Dfs (cur+1, len-sticks[cur],level+1)) + return true; AUsed[cur] =false;//Backtracking at return false; -}Else { - if(cur >= N-1)return false; - for(inti = Cur;i < n; + + i) {//Pruning - if(Used[i])Continue;//the length of the visit - if(Sticks[i] = = sticks[i-1] &&!used[i-1])Continue;//the same length has been searched without searching. in if(Sticks[i] > left)Continue;//greater than the length of the child reaching Len -Used[i] =true; to if(Dfs (I,left-sticks[i],level))return true; +Used[i] =false;//Backtracking - } the return false; * } $ }Panax Notoginseng intMain () - { the while(Cin >>n,n) { + intsum =0; A for(inti =0; i < n; ++i) { theCIN >>Sticks[i]; + if(sticks[i]> -) - { $n--;i--;Continue; $ } -Sum + =Sticks[i]; - } theSort (sticks,sticks + n,cmp);//Pruning - BOOLEnd =false ;Wuyi for(len = sticks[0]; Len <= sum/2; len++) { the if(Sum%len = =0) {//Pruning -used[0] =true; Wunum = sum/Len; - if(Dfs (0, len-sticks[0],0)) { AboutEnd =true; $cout << Len <<Endl; - Break; - } -used[0] =false;//Backtracking A } + } the if(!end) cout << sum <<Endl; -memset (Used,0,sizeof(used)); $ } the return 0; the}
View Code
HDU 1455 Sticks