Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 126238 | Accepted: 29477 |
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
uva上面提交超时,poj上可以过;
AC代码:
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 1e4+;
int len[N],sum,L,T;
int used[N];
//bool cmp(int x,int y)
//{
// if(x>y) return true;
//}
int cmp(const void *a,const void *b)
{
return *(int *)b-*(int *)a;
}
bool DFS(int m,int left)//m为剩余的木棒数,left为当前正在拼接的木棒和假定的木棒长度L还缺少的长度
{
if(m == && left == )
return true;
if(left == )//一根刚刚拼完
left = L;
for(int i=; i<T; i++)
{
if(!used[i] && len[i]<=left)
{
if(i>)//如果前者已经出现过的不能用,则当前的也不能用
{
if(!used[i-] && len[i] == len[i-])
continue;
}
used[i] = ;
if(DFS(m-,left-len[i]))
return true;
else
{
used[i] = ;
if(len[i] == left || left == L)
return false;
}
}
}
return false;
}
int main()
{
while(scanf("%d",&T) && T)
{ sum = ;
for(int i=;i<T;i++)
{
scanf("%d",&len[i]);
sum = sum + len[i];
}
//sort(len,len+T,cmp); sort 超时
qsort(len,T,sizeof(int),cmp); //从大到小排序
for(L = len[];L<=sum/;L++)
{
if(sum%L) continue;
memset(used,,sizeof(used));
if(DFS(T,L))
{
printf("%d\n",L);
break;
}
}
if(L>sum/) printf("%d\n",sum);
}
return ;
}