Sticks

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Nowhewantstoreturnstickstotheoriginalstate,butheforgothowmanystickshehadoriginally 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 file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. The second line contains the lengths of those parts separated by the space. The last line of the file contains ‘0’. 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个小木块,然后让你拼成若干个同样的高度,看看最小的高度是多少。

这道题涉及的剪枝才是关键,没有剪枝你就等待的是无限超时

1    形成的长度之和肯定能整除这些小木块

2    搜索到总量一半的时候还没有结果的话,那么结果就是sum

3   长度相同的木棍就没必要在处理一遍

4 从大到小的排序处理会更好

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,m,maxx,sum,flag;
int a[1010],book[1010];
bool cmp(int x,int y)
{
    return x>y;
}
void dfs(int x,int y,int z,int u)
{
    int i;
    if(u*z==sum)
    {
        flag=1;
        maxx=z;
        return ;
    }
    if(flag) return ;
    for(i=x; i<=n; i++)
    {
        if(!book[i]&&a[i]<=y)
        {
            book[i]=1;
            if(a[i]==y)
                dfs(1,z,z,u+1);
            else
                dfs(i+1,y-a[i],z,u);
            book[i]=0;
            if(y==z)
                return ;
            while(a[i+1]==a[i])
                i++;
        }
    }
}
int main()
{
    while(scanf("%d",&n)&&n)
    {
        sum=0;
        memset(book,0,sizeof(book));
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a+1,a+n+1,cmp);
        int l=a[1];
        flag=0;
        maxx=sum;
        while(!flag)
        {
            if(sum%l==0)
            {
                dfs(1,l,l,0);
            }
            l++;
            if(l>sum/2)
                break ;
        }
        printf("%d\n",maxx);
    }
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值