Sticks

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

题意:
一根木棍,已知砍断之后具有多少节木棍和截断以后,所得到的各节木棍的长度,求原始木棒的可能最小长度。
思路:这道题用dfs,最重要的是剪枝:木棒的长度一定大于等于最长的木棍的长度且小于等于所有木棍长度的和。把所有木棍的长度从大到小排列,组合木棒时优先使用长的木棍。木棒的长度一定是所有木棍长度的和的约数。在某一个木棒的组合中,对于当前的木棍a[i],如果a[i-1]没有被组合并且a[i] == a[i-1],那么不用考虑a[i]。如果此次是在尝试第i个木棒的第一段,假设a[j]为当前可以被使用的最长的木棍,如果此次组合失败,直接退出搜索,退回到对第i-1个木棒的搜索。因为当a[j]作为第i根木棒的第一段无法组合的话,作为第i + k (k > 0)的木棒的第一段也不行,因为此时所剩下的木棒更少,为其子集。如果能用一段完成一根木棒,就没必要采用多段来组合,因为永远可以用多段来替代一段,却不能用一段来替代多段。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
int n, a[110], sum, m, book[110];
bool cmp(int s, int v)
{
    return s > v;
}  
int dfs(int p, int t, int cnt)
{
    int i;
    if (cnt == m) return 1; // 可以组成木棒
    for (i = p; i < n; i++)
        if (!book[i])
        {
            if (i && !book[i - 1] && a[i] == a[i - 1])
            continue; 
            if (t + a[i] < sum / m)
            {
                book[i] = 1;
                if (dfs(i + 1, t + a[i], cnt))
                return 1;
                book[i] = 0;
                if (t == 0)
                return 0;  
            }
            else if (t+ a[i] == sum / m)
            {
                book[i] = 1;
                if (dfs(0, 0, cnt + 1))
                return 1;
                book[i] = 0;
                return 0; 
            }
        }
    return 0;
}
int main ()
{
    int i, j;
    while(~scanf("%d", &n)&&n)
    {
        sum = m = 0;
        for (i = 0; i < n; i++)
        {
            scanf("%d", a + i);
            sum += a[i];
            if (a[i] > m)
                m = a[i];
        }
        sort(a, a + n, cmp);
        m = sum / m;
        while(m)
        {
            if (sum % m == 0) 
            {
                memset(book, 0,sizeof(book));
                if (dfs(0, 0, 0)) break;
            }
            m--;
        }
        printf("%d\n", sum / m);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值