Sticks POJ - 1011 (暴力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 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

大致题意:乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍 的长度都不超过50个长度单位。然后他又想把这些木棍恢复到为 裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。 请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节 木棍的长度都用大于零的整数表示,最多64个木棍。

思路:暴搜+剪枝。

代码如下

#include <iostream> 
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cstdio>
using namespace std; 
#define ll long long int 
int vis[100];
int lenth[100];
int n;
int flag;
int len;
void dfs(int num,int nlen,int wei)//已用小棒数,现在长度,当前小棒的位置 
{
    if(flag) return;

    else if(nlen==0)//如果当前长度为0,则从后面往前选择一个还未用过的木棒进行拼凑
    {
         int x=n;
         while(vis[x]) x--;
         vis[x]=1;
         dfs(num+1,lenth[x],x-1);
         vis[x]=0;

    }
    else if(nlen==len)//当前可以拼凑出长度为len
    {
        if(num==n)//如果已经用完所有木棒,说明该长度len满足条件
        {
            flag=1;
            return;
        }

        else//还未用完
        dfs(num,0,n);
    }
    else
    {
        for(int i=wei;i>=1;i--)
        {
            if(!vis[i]&&lenth[i]+nlen<=len)
            {
                if(!vis[i+1]&&lenth[i]==lenth[i+1])//如果之前有一个木棒长度和这个一样而且没选,说明这个长度的木棒选了之后不能满足条件,所以这次拼凑就不考虑这个长度的木棒了。这里是一个很重要的剪枝
                continue;

                vis[i]=1;
                dfs(num+1,nlen+lenth[i],i-1);
                vis[i]=0;
            }
        }
    }
}
int main() 
{  
    while(scanf("%d",&n)&&n!=0)
    {
        flag=0; 
        int sum=0;

        for(int i=1;i<=n;i++)
        {
           scanf("%d",&lenth[i]);
           sum+=lenth[i];
        }

        sort(lenth+1,lenth+1+n);
        for(len=lenth[n];len<=sum;len++)
        {
            if(sum%len==0)
            {
                memset(vis,0,sizeof(vis));
               dfs(0,0,n);
            }

            if(flag)
            break;  
        }

        printf("%d\n",len);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值