文章标题 HDU 1455 : Sticks(dfs+剪枝)

Sticks

Description
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 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
题意: 有n根木棒,将这n跟木棒组合起来,使其组合的所有木棒长度一样,然后要使这木棒的长度最短。
分析: 有dfs,由题意知,组合成的木棒的长度在max(stick【i】)~sum(stick【i】)之间,所以遍历一遍,当遇到符合的就是要找的最短的木棒的长度。
代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue> 
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
int n; 
int total;//连起来木棒的总数 
int curr_len;//当前木棒的长度 
struct Stick{
    int length;
    int vis;//判断是否已经被标记
};
Stick stick[70];
bool cmp(Stick a,Stick b){
    return a.length>b.length;
}
//s表示已经组合成的木棒的数目,len表示当前的木棒长度,pos表示当前的木棒位置
int dfs(int s,int len,int pos){
    if (s==total)return 1;
    for (int i=pos+1;i<n;i++){//从下一根木棒开始
        if (stick[i].vis)continue;//如果已经被标记,直接进入下一根
        if (len+stick[i].length==curr_len){//刚好等于所求的curr_len
            stick[i].vis=1;
            if (dfs(s+1,0,-1))return 1;
            stick[i].vis=0;
        }
        else if (len+stick[i].length<curr_len){//加起来下雨curr_len
            stick[i].vis=1;
            if (dfs(s,len+stick[i].length,i))return 1; 
            stick[i].vis=0;
            if (len==0)return 0;
            //剪枝:如果当前搜索时,前边的长度为0,而第一根没有成功的使用,
            //说明第一根始终要被废弃,所以这种组合必定不会成功
            //此处的剪枝必须有,因为这里的剪枝会节省很多的无用搜索
            while (stick[i].length==stick[i+1].length)i++;
        }
    } 
    return 0;
}
int main ()
{
    while (scanf ("%d",&n)&&n){
        int sum=0;
        for (int i=0;i<n;i++){
            scanf ("%d",&stick[i].length);
            sum+=stick[i].length;
            stick[i].vis=0;
        }
        sort (stick,stick+n,cmp);
        for (curr_len=stick[0].length;curr_len<=sum;curr_len++){
            if (sum%curr_len)continue;//当除不尽时说明不符合情况直接跳过
            total=sum/curr_len;//当一根木棒的长度为curr_len时,木棒的数目
            if (dfs(1,0,-1)){//成功时
                printf ("%d\n",curr_len);
                break;
            }
        } 
    }       
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值