N根短木棒 能够拼成几根长度相等的长木棒 求长木棒的长度 如果答案不止一种 输出最小的
Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Sample Output
6
5
1 # include <cstdio> 2 # include <cmath> 3 # include <iostream> 4 # include <cstring> 5 # include <algorithm> 6 using namespace std ; 7 8 int sum , num; 9 int a[70] ; 10 bool v[70] ; 11 int len , n; 12 13 bool cmp(const int &x , const int &y) 14 { 15 return x > y ; 16 } 17 18 bool dfs(int count , int L , int pos) //已完成的数量 当前木棒长度 位置 19 { 20 if (len == sum) 21 return 1 ; 22 if (count == num) 23 return 1 ; 24 for (int i = pos ; i < n ; i++) 25 { 26 if (v[i]) 27 continue ; 28 if (L + a[i] == len) 29 { 30 v[i] = 1 ; 31 if (dfs(count+1 , 0 , 0)) 32 return 1 ; 33 v[i] = 0 ; 34 return 0 ; 35 } 36 else if (L + a[i] < len) 37 { 38 v[i] = 1 ; 39 if (dfs(count , L+a[i] , i+1)) 40 return 1 ; 41 v[i] = 0 ; 42 if (L == 0) //说明有一根木棒没有派上用场 43 return 0 ; 44 while (a[i] == a[i+1]) //如果下一根的长度和这根一样 则继续搜索下面的 45 i++ ; 46 } 47 } 48 return 0 ; 49 } 50 51 int main() 52 { 53 //freopen("in.txt","r",stdin) ; 54 while (scanf("%d" , &n) , n) 55 { 56 sum = 0 ; 57 int i ; 58 for (i = 0 ; i < n ; i++) 59 { 60 scanf("%d" , &a[i]) ; 61 sum += a[i] ; 62 } 63 sort(a,a+n,cmp) ; 64 if (a[0] > sum - a[0]) //如过第1根木棒比剩下的木棒和 还要长 65 { 66 printf("%d\n" , sum) ; 67 continue ; 68 } 69 for (len = a[0] ; len <= sum ; len++) //一根完整木棒的长度肯定大于最长的小木棒 70 { 71 if (sum % len) 72 continue ; 73 memset(v , 0 , sizeof(v)) ; 74 num = sum/len ; 75 if (dfs(0,0,0)) 76 { 77 printf("%d\n" , len) ; 78 break ; 79 } 80 } 81 } 82 return 0 ; 83 84 }