POJ 1011 (DFS)

本文介绍了一个有趣的编程问题:如何通过已知的切割后的棍子片段,逆向推导出原始棍子的最短可能长度。文章提供了一段C++代码示例,详细解释了解决方案的实现过程。

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

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 <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <cmath>
#include <vector>

using namespace std;

const int maxn = 70;
int n, l[maxn], sum, flag, vis[maxn];

int cmp(int a, int b) {
    return a > b;
}

bool DFS(int num, int nl, int rel, int now)//num为已经用过的小棒数目,nl为现在已经有多长,rel是总共要组合成多长,now是现在已经搜索到哪根棒了
{
    if (num == n) return true;
    int sample = -1;
    for (int i = now; i < n; i++) {
        if (vis[i] || l[i] == sample) continue;//剪枝第三刀:等长的只搜索一次
        vis[i] = 1;
        if (nl + l[i] < rel) {
            if (DFS (num + 1, nl + l[i], rel, i)) return true;
            else sample = l[i];
        } else if (nl + l[i] == rel) {
            if (DFS (num + 1,  0, rel, 0)) return true;//还要把原来跳过的等长的再看一遍,考虑一遍
            else sample = l[i];
        }
        vis[i] = 0;
        if (nl == 0) break;//剪枝第四刀:如果没有配对的,就跳出去
    }
    return false;
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen ("in.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    while (scanf ("%d", &n) != EOF) {
        if (n == 0) break;
        sum = 0;
        flag = 0;
        memset (l, 0, sizeof(l));
        for (int i = 0; i < n; i++) {
            scanf ("%d", &l[i]);
            sum += l[i];
        }
        sort (l, l + n, cmp);
        for (int i = l[0]; i <= sum / 2 + 1; i++) {//剪枝第一刀:下限为最长的棍长,上限是一半多一个
            if (sum % i != 0) continue;//剪枝第二刀:如果不是总长度的余数
            memset (vis, 0, sizeof(vis));
            if (DFS (0, 0, i, 0)) {
                flag = 1;
                printf ("%d\n", i);
                break;
            }
        }
        if (flag == 0) printf ("%d\n", sum);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值