一、视频讲解
蓝桥杯真题讲解:买瓜 (DFS+剪枝优化)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/889e3fdf54b327d6cbd18f4dd0ba0dc3.png)
二、正解代码
#include<bits/stdc++.h>
#define endl "\n"
#define deb(x) cout << #x << " = " << x << '\n';
#define INF 0x3f3f3f3f
using namespace std;
const int N = 100;
double a[N];
double s[N];
int n, m;
int ans = INF;
void dfs(int u, double w, int cnt) {
if(w == m){
ans = min(ans, cnt);
return;
}
if(u >= n)return;
if(cnt >= ans)return;
if(w > m)return;
if(w + s[u] < m)return;
dfs(u + 1, w + a[u], cnt);
dfs(u + 1, w + a[u] / 2.0, cnt + 1);
dfs(u + 1, w, cnt);
}
void solve()
{
cin >> n >> m;
for(int i = 0; i < n; i ++){
cin >> a[i];
}
sort(a, a + n, [&](int x, int y){return x > y;});
for(int i = n - 1; i >= 0; i --){
s[i] = s[i + 1] + a[i];
}
dfs(0, 0.0, 0);
if(ans == INF)ans = -1;
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
while(t--)
solve();
}