hduoj 1455 && uva 243 E - Sticks

时间:2022-06-29 15:54:21

http://acm.hdu.edu.cn/showproblem.php?pid=1455

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=243

uva开头描述:

307 - Sticks

Time limit: 3.000 seconds

hduoj 开头描述:

E - Sticks

Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

 
 
题目描述:
 

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 file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. 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

Sample Output

6
5 分析:
uva会TLE , hduoj AC

hduoj 1455 && uva 243 E - Sticks


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]; 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 ;
}