DFS之剪枝与优化1:165
作者:
总打瞌睡的天天啊
,
2024-10-22 09:58:08
,
所有人可见
,
阅读 3
//跟上一题的贪心不同,猫是可以随便放的
#include <cstdio>
#include<iostream>
#include <algorithm>
using namespace std;
const int N = 20;
int n,m;
int a[N],sum[N];
int ans = 2e9;
void dfs (int u,int res) {
if (res >= ans) return ;
if (u > n) {
ans = min (ans,res);
return ;
}
for (int i = 1;i <= res;i++) {
if (sum[i] + a[u] <= m) {
sum[i] += a[u];
dfs (u + 1,res);
sum[i] -= a[u];
}
}
sum[res + 1] = a[u];
dfs (u + 1,res + 1);
sum[res + 1] = 0;
}
int main () {
cin >> n >> m;
for (int i = 1;i <= n;i++) cin >> a[i];
sort (a + 1,a + 1 + n,[](int p,int q) {
return p > q;
});
dfs (1,1);
cout << ans << endl;
return 0;
}