165. 小猫爬山

唉,好久没写题了,全面退化...

翰翰和达达饲养了 N 只小猫,这天,小猫们要去爬山。

经历了千辛万苦,小猫们终于爬上了山顶,但是疲倦的它们再也不想徒步走下山了(呜咕>_<)。

翰翰和达达只好花钱让它们坐索道下山。

索道上的缆车最大承重量为 W,而 N 只小猫的重量分别是 (C_1,C_2...C_N)

当然,每辆缆车上的小猫的重量之和不能超过 W。

每租用一辆缆车,翰翰和达达就要付 1 美元,所以他们想知道,最少需要付多少美元才能把这 N 只小猫都运送下山?

输入格式

第 1 行:包含两个用空格隔开的整数,N 和 W。

第 2..N+1 行:每行一个整数,其中第 i+1 行的整数表示第 i 只小猫的重量 Ci。

输出格式

输出一个整数,表示最少需要多少美元,也就是最少需要多少辆缆车。

数据范围

(1≤N≤18)
(1≤Ci≤W≤10^8)

思路

搜索,一开什么都没想直接爆搜t了,需要一些剪枝技巧

  1. 如果当前使用的缆车数已经比res要大了,就直接返回,不再继续向下搜了
  2. 为了能最大化地利用剪枝,需要优化搜索顺序,因为对于一只猫来说它的体重越大,可以供选择的车就越少,所以在搜索中尽量使用体重较大的猫来选择车,这样就可以在本层产生更少的下层分枝,从而最大化利用剪枝,剪掉不必要的分枝。

TLE代码

这个思路上都是错的

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 20, INF = 0x3f3f3f3f;

int n, w;
int c[N], st[N];
int res = INF;

void dfs(int a, int b, int cnt){ // 当前车的容量,已经选择的车辆数,剩余猫的数量
    if(b >= res) return;
    if(cnt == 0){
        res = min(res, b);
        return;
    }
    for(int i = 0; i < n; i ++)
        if(st[i] == 0){
            st[i] = 1;
            if(a >= c[i]) dfs(a - c[i], b, cnt - 1);
            else dfs(w - c[i], b + 1, cnt - 1);
            st[i] = 0;
        }
}

int main(){
    cin >> n >> w;
    
    for(int i = 0; i < n; i ++) cin >> c[i];
    
    dfs(w, 1, n);
    
    cout << res << endl;
    
    return 0;
}

正确思路

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 20, INF = 0x3f3f3f3f;

int n, w;
int c[N], st[N], l[N];
int res = INF;

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

void dfs(int u, int v){
    if(v >= res) return;
    if(u == n){
        res = min(res, v);
        return;
    }
    
    for(int i = 0; i < v; i ++)
        if(l[i] >= c[u]){
            l[i] -= c[u];
            dfs(u + 1, v);
            l[i] += c[u];
        }
    
    l[v] = w - c[u];
    dfs(u + 1, v + 1);
    l[v] += c[u];
}

int main(){
    cin >> n >> w;
    
    for(int i = 0; i < n; i ++) cin >> c[i];
    
    sort(c, c + n, cmp); // 降序排序,确保每次用体重较大的猫来选车
    
    l[0] = w;
    dfs(0, 1);
    
    cout << res << endl;
    
    return 0;
}
原文地址:https://www.cnblogs.com/tomori/p/14747606.html