POJ 1011 Sticks

博客讲述 George 将等长木棍随机切割,各部分最长 50 单位,他想恢复原状却忘了原数量和长度。需设计程序计算原木棍最小可能长度,输入为切割后木棍数量及各部分长度,输出为原木棍最小长度。

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

#include<set>
#include<map>
#include<stack>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = 1e3 + 5;
int n, cnt, len;
int a[maxn],sum,vis[maxn];
int cmp(int x, int y)
{
    return x > y;
}
int dfs(int num, int val)
{
    if (num == cnt)        //当num等于剪切的段数时返回
        return 1; 
    if (val == len)           //当val=len时开始下一个搜索
        return dfs(num + 1, 0);      
    int temp = 0;
    for (int i = 1; i <= n; i++)
    {
        if (!vis[i] && val + a[i] <= len)
        {
            vis[i] = 1;
            if (dfs(num, val+a[i]))         
                return 1;
            
             vis[i] = 0;
             if(val == 0 || val + a[i] == len)//剪枝 代表不能将所有的拼出len 直接返回0 
                return false;
        }
    }
    return 0;
}
int main()
{
    while (std::cin >> n && n)
    {
        sum = 0;
        for (int i = 1; i <= n; i++)
        {
            std::cin >> a[i];
            sum += a[i];
        }
        std::sort(a+1, a + n+1,cmp);   //排序 用于剪枝
        for (int i = a[1]; i <= sum; i++)  //从a数组最大的数开始遍历 到sum停止
        {
            if (sum % i != 0) continue;
            cnt = sum / i;
            len = i;
            memset(vis, 0, sizeof(vis));
            if (dfs(0,0))
            {
                std::cout << i << std::endl;
                break;
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值