[回溯&&剪枝]Sticks UVA307


 Sticks 

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

题意:
George拿了一些相同长度的棍子,然后随意的把这些棍子切成一段一段的棍子(每段长度都不会超过50个单位长)。现在他想要把这些一段一段的棍子拼回原来的样子,但是他忘了他原来带多少根棍子来,并且也忘了原来每根棍子的长度。请帮助他设计一个程式算出这些棍子原来可能的最小长度。
这道题就是典型的回溯搜索剪枝题目。剪枝条件较多,不然就超时
剪枝条件:
1.原来的长度取值范围是切割成小木棍的最长长度到小木棍长度总和之间。
2.小木棍总和长度一定可以整除原来的长度。
3.对小木棍长度进行从大到小排序,进行判定的时候优先选择较长的木棍,递归次数较少。
4.小段在每组成一个木棍的过程中, 如果有遇到一个木棍,他的长度和上一根不能组成的长度一样,就可以跳过这次判断,因为前一根长度一样不能组成,那么这根一定也不能。
5.如果在组合过程中,第一根木棍没有用上,那么以后它也用不上。
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int arry[100],vis[100];
int n,m,judge,len;

bool cmp(int x,int y)
{
    return x>y;
}

void dfs(int pos,int num,int lenth)
{
    if(judge) return;
    if(num==m/len)
    {
        judge=1;
        return;
    }
    int i,pre=-1;//剪枝条件4,pre记录上一次组合的长度
    for(i=pos;i<n;i++)
    {
        if(vis[i]==0&&arry[i]!=pre)
        {
            pre=arry[i];
            if(lenth+arry[i]<len)
            {
                vis[i]=1;
                dfs(i+1,num,lenth+arry[i]);
                vis[i]=0;
                if(lenth==0) return;//剪枝条件5
            }
            else if(lenth+arry[i]==len)
            {
                vis[i]=1;
                dfs(0,num+1,0);
                vis[i]=0;
                return;
            }
        }
    }
    if(judge) return;
}

int main()
{
    while(cin>>n&&n)
    {
        memset(vis,0,sizeof(vis));
        m=0,judge=0,len=0;
        for(int i=0;i<n;i++)
        {
            cin>>arry[i];
            m=m+arry[i];
            if(arry[i]>len) len=arry[i];
        }
        sort(arry,arry+n,cmp);//剪枝条件3
        for(;len<=m;len++)//剪枝条件1
        {
            if(m%len==0)//剪枝条件2
            {
                dfs(0,0,0);
                if(judge==1) break;
            }
        }
        cout<<len<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值