POJ 1011 Sticks【dfs】

本文介绍了一个解决在切割木棍后还原原始状态的问题的算法。通过优化搜索过程,减少不必要的尝试,实现了对原始木棍长度的有效计算。重点讨论了剪枝策略和贪心算法的应用,以及如何通过数学验证确保解决方案的正确性和效率。

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

Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 132725 Accepted: 31172

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

无论是后台数据还是需要的算法剪枝程度,真的是无法挑剔的一个题,剪枝无果,贪心WA,最终还是看的大牛题解找到了思路AC的。

重要剪枝:

1、一定是几根或者一根木棍组成大木棍,所以我们不必要从长度为1开始枚举,我们从最长的那根木棍开始枚举。

2、我们用pre标记,上一个建组的长度没有必要建组第二次。

3、组成的最终长度绝对是所有小木棍长度的和的因字数,所以枚举j的时候判断一下sum%j==0再进入dfs。

4、回溯的该跳出就跳出、

AC代码:(参考自http://blog.youkuaiyun.com/woshixingaaa/article/details/5589100)

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int a[65];
int vis[65];
int s, j, n;
bool cmp(int a, int b)//从大到小排序
{
    return a > b;
}
bool dfs(int sum, int k, int cont)
{
    if (cont == s) return true;//达到目标
    else if (sum == j) return dfs(0, 0, cont + 1);//拼成一根之后,拼下一根
    else
    {
        int pre, i;//pre剪重复情况。
        for (pre = 0, i = k; i < n; i++)
        {
            if (vis[i] && a[i] != pre && a[i] + sum <= j)
            {
                pre = a[i];
                vis[i] = false;
                if (dfs(sum + a[i], i + 1, cont)) break;
                vis[i] = true;
                if (k == 0) return false;//如果回溯到这里,跳出这种情况。
            }
        }
        if (i == n) return false;
        else return true;
    }
}
int main()
{
    int i, sum;
    while(~scanf("%d",&n),n)
    {
        for (i = sum = 0; i<n; i++)
        {
            scanf("%d",&a[i]);
            sum += a[i];
        }
        sort(a, a+ n,cmp);
        for (j = a[0]; j< sum; j++)
        {
            if(sum % j== 0)
            {
                s = sum / j;
                memset(vis, true,sizeof(vis));
                if (dfs(0, 0, 0)) break;
            }
        }
        printf("%d\n",j);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值