UVA - 307 Sticks (dfs+剪枝)

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 ‘0’.

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

题意:给你一堆被切断的木棒,最多50段。然后让你求他们被切断前的最小长度(没说原来有几根,注意,可能只有一根哦)。

思路:因为你不知道原来有多少根,以及范围,一不小心就会超时,所以剪枝很重要。

  首先,查找范围的缩小,从大到小排序,原来的长度肯定在最大的一段max(a[i)]与总长度之间sum(a[i])。
但我们并不需要搜到sum(a[i]),搜到sum(a[i])/2即可。因为原来的长度肯定能被sun除尽,如果连sum/2都不成立,只有原来的长度是sum了。

另外 两个重要的剪枝:

1:如果前面的和其相等的长度没有用到,那么这段也用不到,没有必要去搜。

2:如果第一段都不能用,那么这个长度肯定有问题。

代码如下:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[100];
int vis[100];
int n,minn,k;
int dfs(int l,int pos,int num)
{
    if(l==minn)
    {
        l=0;  //注意,重新复位0
        num++;  //计算段数1
        pos=0;   //从0重新查找;
    }
    if(num==k)
        return 1;
    for(int i=pos+1; i<n; i++)
    {
        if(l+a[i]<=minn&&vis[i]==0)
        {
            if(vis[i-1]==0&&a[i-1]==a[i])continue;  //前一段未用,后面的和其相等的同样不用
            vis[i]=1;
            if(dfs(l+a[i],i,num))return 1;
            vis[i]=0;
            if(l==0)return 0;//重要,可能已经组好了几段,l重新为0,但剩下的组不了了。
        }
    }
    return 0;
}
int cmp(int a,int b)
{
    return a>b;
}
int main()
{
    while(~scanf("%d",&n)&&n)
    {
        int sum=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        memset(vis,0,sizeof(vis));
        sort(a,a+n,cmp);
        for(minn=a[0]; minn<=sum/2; minn++)
        {
            if(sum%minn)continue;
            k=sum/minn;
            vis[0]=1;  //第一段肯定可以配对,否则必错
            if(dfs(a[0],0,0))
            {
                printf("%d\n",minn);
                break;
            }
        }
        if(minn>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、付费专栏及课程。

余额充值