首页 > 其他分享 >小猫爬山

小猫爬山

时间:2022-09-02 14:58:02浏览次数:59  
标签:小猫 int sum 爬山 dfs ans return include

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

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 20;

int n, m;
int w[N];
int sum[N];
int ans = N;

void dfs(int u, int k)
{
    // 最优性剪枝
    if (k >= ans) return;
    if (u == n)
    {
        ans = k;
        return;
    }

    for (int i = 0; i < k; i ++ )
        if (sum[i] + w[u] <= m) // 可行性剪枝
        {
            sum[i] += w[u];
            dfs(u + 1, k);
            sum[i] -= w[u]; // 恢复现场
        }

    // 新开一辆车
    sum[k] = w[u];
    dfs(u + 1, k + 1);
    sum[k] = 0; // 恢复现场
}

int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i ++ ) cin >> w[i];

    // 优化搜索顺序
    sort(w, w + n);
    reverse(w, w + n);

    dfs(0, 0);

    cout << ans << endl;

    return 0;
}

标签:小猫,int,sum,爬山,dfs,ans,return,include
From: https://www.cnblogs.com/xjtfate/p/16649863.html

相关文章

  • 小度养小猫
    https://matiji.net/exam/contest/contestdetail/55?type=4constintN=1e5+7;intn,k,c[N];voidsolve(){longlongans=0;scanf("%d%d",&n,&k......
  • [AcWing 165] 小猫爬山
    DFS剪枝点击查看代码#include<bits/stdc++.h>usingnamespacestd;typedeflonglongLL;constintN=50+10;intn,m;intw[N];intsum[N];//每组......