UESTC Training for Search Algorithm——L

Sticks

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

Central Europe 1995

 

 

/*算法思想:
  我用DFS做的,先将所有的木棍从大到小排序,然后从最大的木棍开始枚举木棍能
  拼接的长度len,要是能拼接,退出循环,输出结果
  剪枝1:要是这跟木棍不能用来拼接,那么其他的和他长度相等的木棍也不能拼接
  剪枝2:不能找到一根长度为len的木棍,直接退出搜索,以后也不能找到了
*/

/*CODE*/
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
#define N 100
using namespace std;
int a[N],sum,n,len;
bool fg[80];
bool cmp(int a,int b)
{
    return a>b;
}
bool dfs(int v,int left,int tot)  //DFS,当前用到第v根木棍了,还剩下len凑够一根长度为len的木棍,总的木棍长度还剩tot
{
    if(tot==len) return true;  //如果总的木棍长度还剩tot,一定能够凑够
    for(int i=v;i<n;i++)
    if(!fg[i] && a[i]<=left)  //找一根能够用来拼凑的木棍
    {
        fg[i]=true;
        if(a[i]==left)
        {
            if(dfs(0,len,tot-a[i])) return true;  //找新的一根长度为len的木棍
        }
        else if(dfs(i+1,left-a[i],tot-a[i])) return true;
        fg[i]=false;
        if(a[i]==left) return false;  //不能找到一根新的长度为len的木棍,肯定不能找到了,返回false
        if(tot==sum) return false;  //用于第一次DFS,要是不能找到,返回false
        if(left==len) return false;  //不能找到一根长度为len的木棍,返回false
        while(a[i]==a[i+1]) i++;  //相同的木棍,上一个满足条件找了不能找到,这一个也一样的不能
    }
    return false;
}
int main()
{
    while(scanf("%d",&n),n!=0)
    {
        sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a,a+n,cmp);
        memset(fg,0,sizeof(fg));
        for(len=a[0];len<=sum;len++)
        {
            if(sum%len!=0) continue;
            if(dfs(0,len,sum)) { printf("%d\n",len); break; }
        }
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值