POJ1011 Sticks

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

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

中文:

Description

乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过50个长度单位。然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节木棍的长度都用大于零的整数表示。

Input

输入包含多组数据,每组数据包括两行。第一行是一个不超过64的整数,表示砍断之后共有多少节木棍。第二行是截断以后,所得到的各节木棍的长度。在最后一组数据之后,是一个零。

Output

为每组数据,分别输出原始木棒的可能最小长度,每组数据占一行。

Sample Input

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output

6
5

Source

Translator

北京大学程序设计实习, Xie Di
 
 

正解:搜索+各种强力剪枝

解题报告:

  明天就要去北京参加夏令营了,今晚练一练手感。
  一直知道这道经典搜索题,然而一直没有打。今天打了一下,高兴地一遍过样例,然后交一发高兴地TLE。于是自己yy出了几个剪枝,调了一下,感觉快了很多,然而交了之后还是TLE,

  无奈上网蒯剪枝,发现如果当前需要搜一根新棒并且当前最长的那根用进去不可以那么可以直接return,这个强力剪枝让我直接AC了。

  调了1个多小时。。。

  其他的剪枝还是比较好想到的吧。

 //It is made by jump~
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#ifdef WIN32
#define OT "%I64d"
#else
#define OT "%lld"
#endif
using namespace std;
typedef long long LL;
const int MAXN = ;
int n;
int a[MAXN];
int ans,total;
int ljh;
bool ok;
bool use[MAXN]; inline int getint()
{
int w=,q=;
char c=getchar();
while((c<'' || c>'') && c!='-') c=getchar();
if (c=='-') q=, c=getchar();
while (c>='' && c<='') w=w*+c-'', c=getchar();
return q ? -w : w;
} inline bool cmp(int q,int qq){ return q>qq; } inline void Init(){
total=;
for(int i=;i<=n;i++) a[i]=getint(),total+=a[i];
sort(a+,a+n+,cmp);
ans=a[]; ok=false;
memset(use,,sizeof(use));
} inline void dfs(int now,int len,int zong){
if(zong==n) { ok=; return ; }
int cun=-;//上一个不可行的值
for(int i=now;i<=n;i++) {
if(use[i] || cun==a[i]) continue;
use[i]=;
if(a[i]+len<ans){
dfs(i,a[i]+len,zong+);
if(ok) return ;
else cun=a[i];
}
else if(a[i]+len==ans){
dfs(,,zong+);//从0开始
if(ok) return ;
else cun=a[i];
}
use[i]=;
if(len==) break;//构建新棒时,对于新棒的第一根棒子,在搜索完所有棒子后都无法组合,则说明该棒子无法在当前组合方式下组合,不用往下搜索(往下搜索会令该棒子被舍弃),直接返回上一层
}
} inline void solve(){
while(scanf("%d",&n)!=EOF) {
if(n==) break;
Init();
for(;ans<=total-ans;ans++) //只需判断到一半
if(total%ans==) {
dfs(,,);
if(ok) break;
}
if(ok)
printf("%d\n",ans);
else printf("%d\n",total);
}
} int main()
{
solve();
return ;
}