Sticks
描述
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.
输入
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.
输出
The output should contains the smallest possible length of original sticks, one per line.
样例输入
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
样例输出
6
5
#include<bits/stdc++.h> using namespace std; int a[100],vis[100]; int sum,flag,n; int cmp(int x,int y) { return x>y; } int dfs(int need,int num)//need为当前搜索的木棒长度,num为剩余木棒数量 { if(need==0&&num==0)return 1;//当need=0且num=0时说明搜索成功 if(need==0&&num!=0)need=flag;//当前木棒连接成功,进行新的木棒搜索 for(int i=1;i<=n;i++) { if(vis[i]==0&&need>=a[i])//木棒i仍未被使用且适用于当前的搜索 { vis[i]=1; //木棒i标记为已使用 int k=dfs(need-a[i],num-1);//进行下一层搜索 if(k==1)return 1;//搜索成功,直接返回结果 vis[i]=0;//回溯将木棒标记为未使用 if(a[i]==need||flag==need)break;/* 由于当前need的在dfs(need-a[i],num-1)中已被证明无法与剩余木管实现组合,故当a[i]==need|| flag==need时,若有a[i]或flag长度的木条存在时搜索无法成功,剪枝; /*/ while(a[i]==a[i+1])i++;//剪枝,再次搜索与当前木棒长度相同的木棒是无意义的 } } return 0; } int main() { while(scanf("%d",&n),n) { sum=0,flag; for(int i=1;i<=n;i++) { scanf("%d",&a[i]); sum+=a[i]; } sort(a+1,a+n+1,cmp);//从大到小排序 for(int i=a[1];i<=sum;i++) { memset(vis,0,sizeof(vis)); flag=i; if(sum%i==0)//当sum为i的整数倍数说明i可能作为木棍的原长 { int mark=dfs(0,n); if(mark==1)break;//深搜成功当前flag为木棍的原长 } } printf("%d\n",flag); } }
浙公网安备 33010602011771号