POJ1011 Sticks

来源:互联网 发布:菲律宾4g网络制式 编辑:程序博客网 时间:2024/05/18 01:11

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

95 2 1 5 2 1 5 2 141 2 3 40

Sample Output

65


题意:一开始有若干个一样长的木棒,一个人去把这些木棒随机砍成不同的长度,砍完之后又想将这些木棒还原,但并不知道这些木棒原来的长度和数量,给定n个被砍之后的木棒的长度,将其还原成若干个长度尽量短的木棒,求出木棒长度。

据说这是一道经典的搜索题,通过dfs和一些减枝来写。

从假定的长度逐渐递增进行搜索。

而减枝的内容和注意的几点为:

1.因为木棒的长度是不均匀的,所以拼成之后的木棒的长度一定是大于等于这些木棒的最长长度,小于等于这些木棒长度的总和。

2.木棒的长度是会被所有木棒长度总和整除的。

3.当一个木棒不能凑出这个长度的时候,和他相同长度的木棒也凑不出来。

4.DFS的参数列表为:假定的木棒长、拼成这个木棒长还需要多长、还剩下多少根木棒。当需要的长度和剩下的木棒都为0时,则这个木棒便是这么多。

5.因为求最小,所以从最小长度开始搜(即木棒中最长的)。


代码如下:

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define N 100int a[N],n,vis[N];int cmp(int a,int b){return a>b;}int DFS(int len,int remain,int num){if(remain==0&&num==0) return len;if(remain==0) remain=len;for(int i=1;i<=n;i++){if(vis[i]) continue;if(remain>=a[i]){vis[i]=1;if(DFS(len,remain-a[i],num-1)) return len; vis[i]=0; if(a[i]==remain||len==remain) break; while(a[i]==a[i+1]) i++;}}return 0;}int main(){    int i,j,sum,k;    while(scanf("%d",&n),n)    {    sum=0;    for(i=1;i<=n;i++){  scanf("%d",&a[i]);          sum+=a[i];  }    sort(a+1,a+1+n,cmp);      for(i=a[1];i<=sum;i++)  {  memset(vis,0,sizeof(vis));  if(sum%i==0)   {    k=DFS(i,0,n);  if(k) break; }   }    cout<<k<<endl;    }return 0;}



1 0