1534: Sticks

1534: Sticks


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s8192K1032159Standard

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

 

 


This problem is used for contest: 119  150 

 

 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,sum,num,len;
int vis[100],a[100];
int flag;
bool cmp(int x,int y){return x>y;}
void dfs(int s,int cnt,int left)//s表示开始查询的棍子,cnt表示已经拼好了几个棍子,left表示这根棍子还剩多少没拼好
{
    if(cnt==num)
    {
        if(left==len) flag=1;
        return ;
    }
    //剪枝: 当连续截相等时, 不必再搜, 直接跳过   不加会超时
    int pre=-1;
    for(int i=s;!flag&&i<n;i++)
    {
        if(!vis[i]&&left>=a[i]&&pre!=a[i])
        {
            vis[i]=1;pre=a[i];
            if(left==a[i]) dfs(0,cnt+1,len);
            else dfs(i+1,cnt,left-a[i]);
            vis[i]=0; 
            if(s==0) return ;//important   就是这短短的一句话就可以不超时
             //剪枝: startStick=0 代表这是每个棒子的第一截,找到每条棒子的第一截时, 无需再寻找其他可能的截.  
             //言外之意, 如果第一截还需要重新搜索, 就说明根本无法组成该长度的n个棒子.(因为这一截始终会属于某一棒子).  
        }
    }
}           
int main()
{
    while(scanf("%d",&n)==1&&n)
    {
        sum=0;
        for(int i=0;i<n;i++) {scanf("%d",&a[i]);sum+=a[i];}
        sort(a,a+n,cmp);
        flag=0;
        int cnt;
        for(int i=a[0];i<=sum/2;i++)//只需到sum/2即可,因为如果sum/2还不行,那么只有sum了
        {
            if(sum%i==0)
            {
                memset(vis,0,sizeof(vis));
                num=sum/i;len=i;
                dfs(0,0,len);
                if(flag) {cnt=i;break;}
            }
        }
        printf("%d/n",flag? cnt:sum);
    }
    return 0;
}              

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值