AcWing 165. 小猫爬山 DFS

165. 小猫爬山

https://www.acwing.com/problem/content/description/167/

题目


思路

dfs每一个小猫,对于要不要开新车的状态再进行dfs(注意dfs本质是回溯)

剪枝:1.从大到小排序,后续可选空间变少;2.所得到的方案大于当前最小值时,直接返回

代码

#include <iostream>
#include <algorithm>

using namespace std;
const int N = 20;
int a[N], sum[N];
int n, m, ans = 0x7fffffff;
bool vis[N];

void dfs (int x, int cnt) {
    if (cnt >= ans)
        return;
    if (x == n + 1) {
        ans = min (ans, cnt);
        return;
    }

    //把新车填满
    for (int i = 1; i <= cnt; i ++) //枚举每一辆新车
        if (a[x] + sum[i] <= m) {
            sum[i] += a[x];
            dfs (x + 1, cnt);
            sum[i] -= a[x];
        }
    //开新车
    sum[cnt + 1] = a[x];
    dfs (x + 1, cnt + 1);
    sum[cnt + 1] = 0;
    
}

int main () {
    cin >> n >> m;
    for (int i = 1; i <= n; i ++)
        cin >> a[i];
    sort (a + 1, a + n + 1, greater<int>());

    dfs (1, 0);
    cout << ans << endl;
}

不会做搜索题啊QAQ

posted @ 2022-03-30 15:28  Sakana~  阅读(40)  评论(0编辑  收藏  举报