搜索专题01 DFS 简单应用 (深搜剪枝)

我们今天来看道比较奇葩的简单搜索题…

是一道 USACO的铜组题....是一道英文题 大家要自己翻译一下

USACO BRONZE Bookshelf 2

Farmer John recently bought another bookshelf for the cow library,
but the shelf is getting filled up quite quickly, and now the only
available space is at the top.

FJ has N cows (1 <= N <= 20) each with some height of H_i (1 <= H_i
<= 1,000,000 - these are very tall cows). The bookshelf has a height
of B (1 <= B <= S, where S is the sum of the heights of all cows).

To reach the top of the bookshelf, one or more of the cows can stand
on top of each other in a stack, so that their total height is the
sum of each of their individual heights. This total height must be
no less than the height of the bookshelf in order for the cows to
reach the top.

Since a taller stack of cows than necessary can be dangerous, your
job is to find the set of cows that produces a stack of the smallest
height possible such that the stack can reach the bookshelf. Your
program should print the minimal ‘excess’ height between the optimal
stack of cows and the bookshelf.

本题的大概意思是给出n和b,然后给出n个数,用这n个数中的某些,求出一个和,这个和是>=b的最小值,输出最小值与b的差。

 01.第一想法是01背包的处理 在正常看来 这是一种比较优的做法,但是这就需要你高超的技巧了,一维数组的优化,以及对空间的限制(本题的空间为64M),时间的优化等等等等......复杂度就是一普通01背包的复杂度...这里不再赘述....(还是注意点为好,我第一次就MLE了)
 02.对于这类比较普通的问题来说,暴搜在一定程度上是万能的,那么今天就来说一说如何最优的搜索..

首先,我们得确定要搜什么,拿什么搜 本体当然就是搜一下第一个大于且差最小的即可…..
其次 合理的剪枝将为你的搜索优化到极点(本题的优化。。。自己想吧,我没优化)
最后 注意边界 递归 必须注意的事情 不能有闪失
值得提示的是 有的时候状态时需要还原的 有时候千万不要还原 具体情况具体分析
我先把此题的代码给你们

#include <bits/stdc++.h>
using namespace std;
int a[30], cn[30], n, b, minex;
void dfs(int x, int sum)
{
    if(sum + cn[n] - cn[x] < b) return; 
    if(sum >= b)        
    {
        if(minex > sum-b) minex = sum-b;
        return;
    }
    dfs(x+1, sum);
    dfs(x+1, sum+a[x+1]);
}
int main()
{
    while(cin>>n>>b)
    {
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        cn[0] = 0;
        for(int i = 1; i <= n; i++)
            cn[i] += cn[i-1]+a[i];
        minex = 10000000;
        dfs(0, 0);
        printf("%d\n", minex);
    }
    return 0;
}

最后扯一句 你们敢相信你 本题01背包慢的要死 深搜0ms轻松过…….

来来来 我预报一下 下一篇是做蛋糕 想看剪枝的敬请期待

你可能感兴趣的:(搜索,USACO)