dfs+剪枝

这是一篇关于编程算法的博客,主要介绍了一个解决如何找到切割后棍子原始长度最小值的问题。通过DFS(深度优先搜索)和剪枝策略,程序计算在棍子被切割成多个不超过50单位长度的部分后,原来的棍子可能的最短长度。输入包含切割后的棍子数量和长度,输出是最小原始长度。示例展示了输入输出样例以及C++实现的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 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
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int a[100];
int used[100];
int ans;
int n;
int dfs(int pos,int len,int cnt)  //当前位置,当前组合长度,当前木棒数
{
    if(!len&&cnt>=n) return 1; //木棒数>n并且当前长度不为0直接返回 收索完成
    int last=-1;
    for(int i=pos;i>=0;--i)   //
    {
        if(used[i]||a[i]==last)  continue;  //如果该木棒已经被使用 或者和上一个长度相同 就跳过
        used[i]=1;                            //标记搜过
        if(len+a[i]==ans)                    
            if(dfs(pos-1,0,cnt+1)) return 1;//当前长度+当前木棒刚好等于ans就搜 下一组
            else last=a[i];                
        else if (len+a[i]<ans)            //加上当前长度还不够,就往下试下一根
            if(dfs(pos,a[i]+len,cnt+1)) return 1;
            else last=a[i];
        used[i]=0;        //回溯
        if(len==0) break;
    }
    return 0;
}

int main()
{
    while(cin>>n&&n)
    {
        memset(used,0,sizeof used);
        int sum=0;
        for(int i=0;i<n;i++)
            {
                cin>>a[i];
                sum+=a[i];
            }
        sort(a,a+n);  
        for(ans=a[n-1];ans<=sum;ans++)
            if((sum%ans==0)&&dfs(n-1,0,0)) break;  //从最长的开始搜
        cout<<ans<<endl;

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值