poj1011 sticks

本文探讨了一道经典的DFS题目——棍子恢复问题。题目要求将切割后的棍子部分重新组合成原始棍子,并找到最小可能的原始长度。文章通过详细的代码解析,展示了如何使用深度优先搜索(DFS)算法来解决这个问题。

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

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 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

题意简单说就是本来几根一样长的棍子   被小明乱切(乱切   没切中也是有可能的) 切成了n根小棍子   

要你把n根小棍子恢复原样   可能有多组解

要求输出   每根棍子最短的情况时   棍子长度


据说是极为经典的dfs题

一开始真的不知道怎么搜好(辣鸡无力)闷了1个多小时无奈去看了一下题解   恍然大悟

看完自己敲一A后       细看一下   还是原来那些东西      dfs传参  之前积累的棍长  棍的数量   累加棍的位置


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <stack>

using namespace std;

int stick[70];
bool flag[70];
int len,sum,num,n;//len 棍长   sum所有棍子总长度   num棍数目   n小棍数目

bool dfs(int pre_len,int pre_num,int pos)
{
    if(pre_num==num) return true;
    for(int i=pos;i<n;i++)
    {
        if(flag[i]) continue;
        if(pre_len+stick[i]==len)
        {
            flag[i]=true;
            if(dfs(0,pre_num+1,0)) return true;
            flag[i]=false;//回溯
            return false;
        }
        else if(len>(pre_len+stick[i]))
        {
            flag[i]=true;
            if(dfs(pre_len+stick[i],pre_num,i+1)) return true;
            flag[i]=false;
            if(pre_len==0) return false;//这时 之前一根棍都没有   len>stick[i]
            while(i+1<n&&stick[i]==stick[i+1]) i++;//相邻一样的情况就不用算了
        }
    }
    return false;
}


int main()
{
    while(scanf("%d",&n),n)
    {
        num=sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&stick[i]);
            sum+=stick[i];
        }
        sort(stick,stick+n,greater<int>());
        memset(flag,false,sizeof flag);
        for(len=stick[0];len<=sum;len++)
        {
            if(sum%len) continue;//必须整除
            num=sum/len;//总共棍子的数量
            if(dfs(0,0,0))
            {
                printf("%d\n",len);
                break;
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值