Description
George brought a set of equal-length sticks and cut them randomly, making each stick less than 50 units in length. He then tried to restore the sticks to a pre-cut state, but forgot how many sticks and the initial lengths of the sticks were initially. Please design a program to help George calculate the possible minimum length of the stick. The length of each stick is represented by an integer greater than 0.
Input
The input contains multiple sets of data, each of which consists of two rows. The first line is an integer that does not exceed 64, indicating how many sticks are in total after the chop. The second line is truncated after the length of each section of the stick. After the last set of data, it is a zero.
Output
For each set of data, output the smallest possible length of the original stick, one row for each group of data.
Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Sample Output
6
5
Thinking of solving problems
Dfs idea is not difficult, mainly said pruning (pruning cut not good enough, 47ms over)
1. Length must be divisible by sum
2. Start the search on the longest stick.
3. Sort from large to small, flexible from smallest to largest
4. If you find that you are not using the same last side as yourself, then this one must not be used
5. It's enough to ans-1 the edges.
6. In the "New Edge" when, if not successful, directly exit the good (because the end must be all used)
Code
#include <cstdio>#include <cstring>#include <algorithm>using namespace STD;Const intMAXN = -;intS[MAXN];intVIS[MAXN];intNintAnsBOOLcmpintAintb) {returnA>b;}BOOLDfsint_sum,intNodeintKaseintPint Floor){if(_sum > P)return false;if(Kase = = ans-1)return true;if(_sum = = P && Dfs (0,1, kase+1P1))return true; for(inti = node; I <= N; i + +) {if(Vis[i] = =1)Continue;if(vis[i-1] ==0&& s[i-1] = = S[i])Continue; Vis[i] =1;if(Dfs (_sum+s[i],node+1, Kase,p,2))return true;if( Floor==1) {Vis[i] =0;return false;} Vis[i] =0; }return false;}intMain () { while(scanf("%d", &n) && N) {intsum =0; for(inti =1; I <= N; i + +) {scanf("%d", &s[i]); Sum + = S[i]; } sort (s+1, s+n+1, CMP); for(inti = s[1] ; I <= sum; i + +) {if(i = = sum) {printf("%d\n", i); Break;}//I-Length stick if(sum%i)Continue; ans = sum/i;memset(Vis,0,sizeof(VIS));if(Dfs (0,1,0I1)) {printf("%d\n", i); Break; } } }return 0;}
POJ1011 Sticks dfs+ Pruning