Sticks UVA - 307(切木棍 线性区间dp,线性dp,区间思想。)

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

Time limit     3000 ms

OS     Linux


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 

5 2 1 5 2 1 5 2 1 

1 2 3 4 

Sample Output 

5

1.按递减顺序搜索

2.剪枝: (1).原木棍的长度必须是所有木棍长度之和的约数

(2).搜索原木棍长度只需搜到sum/2 若前面还没成功 答案就只能是sum了

(3).构造一根原木棍的第一根小木棍必须是最长的

(4).2根长度相同的木棍没必要重复搜索

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

int t,w[110],sum,book[110],flag;
bool cmp(int a,int b)
{
    return a>b;
}
void dfs(int step,int sum,int h,int l)/*step:遍历过的棒,sum:棒变化的值,h: 从大到小遍历棒 ,第几个棒,l:原始棒的长度*/
{
    if(flag)
        return ;
    if(step==t)
    {
        if(sum==0)
            flag=1;
        return ;
    }
    if(sum==0)/*棒的重新组合*/
    {
        for(int i=0;i<t;i++)
        {
            if(book[i]==0)
            {
                book[i]=1;
                dfs(step+1,l-w[i],i,l);
                book[i]=0;
                break;
            }
        }
    }
    else
    {
        for(int i=h+1;i<t;i++)
        {
            if(book[i]==0&&sum>=w[i])
            {
                book[i]=1;
                dfs(step+1,sum-w[i],i,l);
                if(flag)
                    return ;
                book[i]=0;
                while(i+1<t&&w[i]==w[i+1])
                    i++;/*2根长度相同的木棍没必要重复搜索*/
            }
        }
    }
    return ;
}
int main()
{
    while(cin>>t&&t)
    {
        sum=0;
        flag=0;
        int ant=-1;
        for(int i=0;i<t;i++)
        {
            cin>>w[i];
            ant=max(ant,w[i]);
            sum+=w[i];
        }
        sort(w,w+t,cmp);
        int i;
        for(i=ant;i<=sum/2;i++)
        {
                if(sum%i==0)
                {
                    memset(book,0,sizeof(book));
                    dfs(0,0,0,i);
                    if(flag)
                        break;
                }
        }
        if(flag)
            cout<<i<<endl;
        else
            cout<<sum<<endl;
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值