PKU 1011


タイトルは以下の通りです.
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

この问题はずっと深さの検索の形式を书いていないで、最近ネット上で1段のとても美しいC++コードを见て、贴ってみんなは分かち合います~~
   
   
   
   
  1. #include     
  2. #include     
  3. #include     
  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 
  17.             if (!used[i] && stick[i] != pre && now + stick[i] <= 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 
  34.         {    
  35.             scanf("%d", &stick[i]);    
  36.             sum += stick[i];    
  37.         }    
  38.         sort(stick, stick + n, greater<int>());    
  39.         done = false;    
  40.         for (len = stick[0]; len <= 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
    "
    , len);    
  49.     }    
  50.     return 0;    
  51. }  

思い切ってACよ~~