uva 307 Sticks搜索

 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.


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.


The output file contains the smallest possible length of original sticks, one per line.


输入

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
输出

6
5
题意:将n节木棒接成m个长度相等的木条,要求木条的长度尽可能的短。

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int a[110];
int v[110],i,t;

bool cmp(int x,int y)
{
    return x>y;
}
int dfs(int len,int n,int pos)//还需要的长度  已使用的棍子个数  从第几根木棍开始拼接,都从大到小开始拼接
{
    if(len==0&&n==0)//拼接完成,没有棍子剩余并且正好拼接
        return 1;
    if(len==0) //当前的这根拼接完成,但是还有棍子没使用完
    {
        pos=-1;//从头开始继续拼接
        len=i;
    }
    for(int j=pos+1; j<t; j++) //pos记录位置,剪枝4  都从大到小开始拼接
    {
        if(a[j]<=len&&v[j]==0) //第j根棍子没有被使用,并且长度小于所剩拼接的长度
        {
            if(j>0)
            {
                if(a[j]==a[j-1]&&v[j-1]==0)//第j根棍子和j-1根棍子长度相等,并且j-1根没有被使用,剪枝1,没有必要找两次长度相等不能用的棍子
                    continue;
            }
            v[j]=1;//使用第j根棍子,标记
            if(dfs(len-a[j],n-1,j))
                return 1;
            else
            {
                v[j]=0; //取消标记,回溯
                if(a[j]==len||len==i) //不能仅仅通过替换最后一根木棒来达到目的,剪枝3   替换第一个根棍子是没有用的,因为就算现在不用,也总会用到这根木棍剪枝2   
                    return 0;
            }

        }
    }
    return 0;
}
int main()
{
    while(~scanf("%d",&t))
    {
        if(t==0)  break;
        int sum=0;
        for(int j=0; j<t; j++)
        {
            scanf("%d",&a[j]);
            sum+=a[j];
        }
        sort(a,a+t,cmp);
        for(i=a[0]; i<=sum/2; i++)//搜索的范围在最长的棍子到所有棍子总和的一半之间
        {
            if(sum%i)  //如果除不尽,则说明不能按照这个长度拼成等长的木棍
                continue;
            memset(v,0,sizeof(v));
            if(dfs(i,t,-1))
            {
                printf("%d\n",i);
                break;
            }
        }
        if(i>sum/2) //大于总和的一半,说明只能拼成一根木棍
            printf("%d\n",sum);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值