题目如下:

Description

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.

Input

The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

Output

The output should contains the smallest possible length of original sticks, one per line.

Sample Input

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output

6
5

这题一直没写好深度搜索的形式,最近在网上看到一段非常精美的C++代码,贴出来大家分享一下~~


  
  1. #include <cstdio>    
  2. #include <algorithm>    
  3. #include <functional>    
  4. using namespace std;    
  5. const int maxN = 64 + 5;    
  6. int n, stick[maxN], len, m;    
  7. bool used[maxN] = {false}, done;    
  8. void dfs(int k, int now, int cnt)    
  9. {    
  10.     if (cnt == m)    
  11.         done = true;    
  12.     else if (now == len)    
  13.         dfs(0, 0, cnt + 1);    
  14.     else {    
  15.         int pre = -1;    
  16.         for (int i = k; i < n; ++i)    
  17.             if (!used[i] && stick[i] != pre && now + stick[i] &lt;= len)    
  18.             {    
  19.                 used[i] = true;    
  20.                 pre = stick[i];    
  21.                 dfs(k + 1, now + stick[i], cnt);    
  22.                 used[i] = false;    
  23.                 if (k == 0 || done)    
  24.                     return;    
  25.             }    
  26.     }    
  27. }    
  28. int main()    
  29. {    
  30.     while (scanf("%d", &n), n > 0)    
  31.     {    
  32.         int sum = 0;    
  33.         for (int i = 0; i < n; ++i)    
  34.         {    
  35.             scanf("%d", &stick[i]);    
  36.             sum += stick[i];    
  37.         }    
  38.         sort(stick, stick + n, greater&lt;int>());    
  39.         done = false;    
  40.         for (len = stick[0]; len &lt;= sum; ++len)    
  41.             if (sum % len == 0)    
  42.             {    
  43.                 m = sum / len;    
  44.                 dfs(0, 0, 0);    
  45.                 if (done)    
  46.                     break;    
  47.             }    
  48.         printf("%d\n", len);    
  49.     }    
  50.     return 0;    
  51. }  

果断AC啊~~