搜索专题训练hdu1455 Sticks

针对已知被切割成多个部分的相同长度木棒,通过编程找出这些木棒原本的最短可能长度。输入包括切割后的木棒部分数量及各部分长度,输出则是原始木棒的最短可能长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意是有n个木棒,他们由相同的长度的若干木棒切开得到,求最小的原始木棒长度。

首先对给出的木棒长度从大到小排序,这样就可以从小到大枚举原始长度,此时根据总长度就可以得到原始根数,(若枚举根数超时)。

对于当前枚举的长度,从大到小依次去尝试选取木棒,若长度小于等于目标长度,则加入,同时标记使用。若达到了目标长度,则将得到根数+1,若根数达到目标根数的时候,则为可行方案。

#include<bits/stdc++.h>
using namespace std;
int n;
int a[105];
int vis[105];
int aim, target;
bool cmp(int a, int b)
{
    return a>b;
}
bool dfs(int cnt, int cur, int pos)// 目标根数, 完成根数, 当前长度
{
    if(cnt == target) return 1;
    if(cur == aim) return dfs(cnt+1, 0, 0);
    for(int i = pos; i < n; ++i)
    {
        if(!vis[i] && cur+a[i]<=aim)
        {
            vis[i] = 1;
            if(dfs(cnt, cur+a[i], i+1))
               return 1;
            vis[i] = 0;
            if(cur == 0) return 0;
            while(i+1 < n && a[i+1]==a[i]) i++;
        }
    }
    return 0;
}

int main()
{
    ios::sync_with_stdio(false);
    while(cin >> n && n!=0)
    {
        int sum = 0;
        for(int i = 0; i < n; i++)
        {
            cin >> a[i];
            sum += a[i];
        }
        sort(a, a+n, cmp);

        for(int i = 1; i <= sum; ++i)//枚举长度, 枚举根数TLE
        if(sum%i == 0)//整除
        {   //cout <<"ok"<< endl;
            aim = i;
            target = sum/i;
            memset(vis, 0, sizeof(vis));
            if(dfs(0, 0, 0))
            {
                cout << aim << endl;
                break;
            }
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值