Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 146700 | Accepted: 34745 |
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
Source
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int d,a[110],vis[110],num,n;
int cmp(int x,int y){
return x>y;
}
int dfs(int nn,int now,int idx){//nn还剩多少棍子要拼,当前拼的木棍的长度,下标
if(now==d){
if(nn==1)
return 1;
if(dfs(nn-1,0,0))
return 1;
return 0;
}
if(now==0){
int i;
for(i=idx;vis[i]&&i<=n;i++);
vis[i]=1;
if(dfs(nn,now+a[i],i+1))return 1;
else {vis[i]=0;return 0;}
}
else {
for(int i=idx;i<=n;i++){
if(!vis[i]&&a[i]+now<=d){
if(!vis[i-1]&&a[i]==a[i-1])//本来剪枝放在dfs后面的,TLE。。
continue;
vis[i]=1;
if(dfs(nn,now+a[i],i+1))
return 1;
vis[i]=0;
}
}
}
return 0;
}
int main(){
while(~scanf("%d",&n)&&n){
int Max=-1,sum=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
Max=max(Max,a[i]);
sum+=a[i];
}
sort(a+1,a+1+n,cmp);
for(d=Max;;d++){//枚举木棍的长度
if(sum%d!=0) continue;
int num=sum/d;
memset(vis,0,sizeof(vis));
if(dfs(num,0,1))
break;
}
printf("%d\n",d);
}
return 0;
}