Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9779 Accepted Submission(s): 2907
Problem 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.
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.
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 file 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
0
Sample Output
6
5
Source
题意:
若干个棍子被切成若干份小棍子,问怎样将这些小棍子组成一些长度最小的一样长的小棍子。
代码:
//DFS+剪枝;先将小木棍从大到小排序,从最长的小木棍开始枚举长度,dfs找到满足的就是最小的。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,num,len,sum;
struct stick
{
int length,mark;
};
stick sti[];
bool cmp(stick x,stick y)
{
return x.length>y.length;
}
int dfs(int cnt,int now,int id) //cnt已经组成的小木棍,now正在组的小木棍的长度,id下标.
{
if(cnt==num) return ; //找到了
for(int i=id;i<n;i++)
{
if(sti[i].mark) continue; //用过了
if(now+sti[i].length==len)
{
sti[i].mark=;
if(dfs(cnt+,,))
return ;
sti[i].mark=;
return ;
}
else if(now+sti[i].length<len)
{
sti[i].mark=;
if(dfs(cnt,now+sti[i].length,i+))
return ;
sti[i].mark=;
if(now==) return ;//如果这一组当前的第一个没有被标的木棍与其他的任意都不能组成目标长度则这个木棍不能用,这种方案不行
while(sti[i].length==sti[i+].length)//加上这个小木棍不行,那么后面和这个小木棍一样长的就不用考虑了
i++;
}
}
return ;
}
int main()
{
while(scanf("%d",&n)&&n)
{
sum=;
for(int i=;i<n;i++)
{
scanf("%d",&sti[i].length);
sum+=sti[i].length;
sti[i].mark=;
}
sort(sti,sti+n,cmp);
for(int i=sti[].length;i<=sum;i++)
{
if(sum%i) continue;//能整除时才能正好分成num份不剩余。
num=sum/i;
len=i;
if(dfs(,,))
{
printf("%d\n",len);
break;
}
}
}
return ;
}