Sticks POJ - 1011

题目链接:点这里

    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 smal
lest 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<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int a[70];
int n;
bool vis[70];

int dfs(int len,int rres,int num)
{
    if(num==0&&rres==0)
        return len;
    if(rres==0)//每一次当剩余的长度为0时都要重新赋值
        rres=len;
    for(int i=n;i>=1;--i)
    if(!vis[i]){
        if(rres>=a[i]){
            vis[i]=true;
            if(dfs(len,rres-a[i],num-1))
                return len;
            vis[i]=false;
            if(rres-a[i]==0||len==rres)
                break;
            while(a[i]==a[i-1])  --i;
        }
    }
    return 0;
}
int main()
{
    while(scanf("%d",&n)!=EOF&&n){
        int sum=0;
        for(int i=1;i<=n;++i){
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        sort(a+1,a+1+n);
        int ans;
        for(int i=a[n];i<=sum;++i) //枚举可能的棍子长度
        if(sum%i==0){   //明显只有sum能整除i的时候才能切割
            memset(vis,false,sizeof(vis));
            ans=dfs(i,0,n);
            if(ans)
                break;
        }
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值