HDU - 1455 G - Sticks

本文介绍了一个关于计算被切割后的木棍如何恢复到最短原始长度的问题,通过深度优先搜索(DFS)并结合剪枝策略来解决该问题。输入包含切割后的木棍片段数量及各段长度,输出是最小可能的原始木棍长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

解题思路:
这其实就是dfs,但是直接dfs就会超时,要去剪枝,将所有的树枝排序,如果第一个是不符合的,比如说需要达到的长度是10,当前的长度是8,但是后面序列里,并没有长度为2的,那么8后面的情况都不需要考虑了,然后还有一些基础的剪枝

代码:
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100];
int sum,maxx;
int t;
bool flag;
int vis[100];
bool cmp(int a,int b)
{
    return a>b;
}
int dfs(int need,int now,int pos,int num)
{
    if(flag)
    {
        return true;
    }
    if(num==t)
    {
        flag = true;
        return true;
    }
    for(int i = pos;i<t;i++)
    {
        if(!vis[i]&&a[i]+now<=need)
        {
            vis[i] = 1;
            if(now+a[i]==need)
                dfs(need,0,0,num+1);
            else dfs(need,a[i]+now,i+1,num+1);
            vis[i] = 0;
            if(now==0)
                return false;
            while(i+1<t&&a[i]==a[i+1])
                i++;
            if(flag)
                return true;
        }
    }
}
int main()
{
    while(cin>>t&&t!=0)
    {
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        flag = false;
        sum = 0;
        maxx = 0;
        for(int i = 0;i<t;i++)
        {
           cin>>a[i];
           sum+=a[i];
           maxx = max(maxx,a[i]);
        }
        sort(a,a+t,cmp);
        if(maxx>sum-maxx)
        {
            cout<<sum<<endl;
            continue;
        }
        for(int i = maxx;i<=sum;i++)
        {
            if(sum%i==0)
            {
                dfs(i,0,0,0);
                if(flag)
                {
                    cout<<i<<endl;
                    break;
                }

            }

        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值