Sticks

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 Outpu

6 
5

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp(int x,int y)
{
    return x>y;
}
int n,l,flag,s[110],book[110];
void dfs(int x,int y,int ll)  //x为剩余木棒的个数,y为此时应从y的位置取木棒,还差ll能把这跟拼好
{
    if(flag)
        return;
    if(x==0&&ll==0)  //木棒全部用完,并且拼成功了
    {
        flag=1;
        return;
    }
    if(ll==0)     //拼成功了一根,开始下一根        {
        y=0;
        ll=l;
    }
    for(int i=y;i<n;i++)
    {
        if(!book[i]&&s[i]<=ll)  //这根木棒没有用过,并且长度小于剩余长度
        {
            if(i>0)
            {
                if(!book[i-1]&&s[i-1]==s[i])  //把和它长度一样的过滤掉
                    continue;
            }
            book[i]=1;
            dfs(x-1,i+1,ll-s[i]);  //剩余木棒数减一。把下一下标传过去,剩余长度
            if(flag)
                return;
            book[i]=0;
            if(s[i]==ll||ll==l)   //这个长度的木棒没有拼成,剩余的长度肯定也拼不成了。
              return;
        }
    }
    return;
}
int main()
{
    int i,j;
    while(~scanf("%d",&n),n)
    {
        flag=0;
        int sum=0;
        for(i=0;i<n;i++)
        {
            scanf("%d",&s[i]);
            sum+=s[i];  //木棒总长度
        }
        sort(s,s+n,cmp); 
        for(int ll=s[0];ll<=sum/2;ll++)  //枚举每一个长度
        {
            if(sum%ll==0)
            {
                l=ll;  //想要的长度
                memset(book,0,sizeof(book));
                dfs(n,0,ll);
                if(flag)  //找到了
                {
                    printf("%d\n",ll);
                    break;
                }
            }
        }
        if(!flag)//没找到,那就只能是一根了
            printf("%d\n",sum);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值