搜索剪枝

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

题解:注释的很详细了。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;

int a[70],b[70];
int n,sum,temp,flag,maxx;

int dfs(int cur,int num)
{
    if(num==0 && cur==0)
        return 1;
    if(cur==0)
        cur=temp;
    for(int i=0; i<n; i++)
    {
        if( a[i]>cur || b[i]==1 )
            continue;
        b[i]=1;
        if(dfs(cur-a[i],num-1))//判断能否拼接完成
            return 1;
        b[i]=0;
        if(a[i]==cur||cur==temp) /*a[i]=cur  或 cur=temp时本来表示即将拼成一根棒,或刚进行新一轮拼接
            (即if中判断的是主问题性质完全相同的子问题)但经过上面的if判断,子问题不能
            完成所有任务,那么整体不可能完成任务,不再考虑,搜索失败(剪枝)*/
            break;
        while(a[i]==a[i+1])// a[i] 无法使用,故与 a[i] 相等的都无法使用;
            i++;
    }
    return 0;
}
bool cmp(int x,int y)
{
    return x>y;
}
int main()
{
    while(cin>>n && n)
    {
        //memset(b,0,sizeof(b));
        sum=0;
        maxx=0;
        for(int i=0; i<n; i++)
        {
            cin>>a[i];
            sum+=a[i];
            if(a[i]>maxx)
                maxx=a[i];
        }
        sort(a,a+n,cmp);
        for(int i=n; i>=1; i--)//最终合成 i 段 木棍;
        {
            if(sum%i==0 && sum/i>=maxx)
            {
                temp=sum/i;//每段长度为temp
                flag=i;
                memset(b,0,sizeof(b));
                if(dfs(temp,n))
                    break;
            }
        }
        cout<<temp<<endl;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值