蓝桥杯真题讲解:买瓜 (DFS+剪枝优化)

蓝桥杯真题讲解:买瓜 (DFS+剪枝优化)

一、视频讲解

蓝桥杯真题讲解:买瓜 (DFS+剪枝优化)
在这里插入图片描述

二、正解代码

//DFS + 剪枝优化
#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;
	}
	//如果n个瓜都遍历完了,那就返回。
	if(u >= n)return;

	//如果当前方案并不优于已有的合法答案,那就返回。
	if(cnt >= ans)return;

	//如果总重量已经超了,那么当前方案不合法。
	if(w > m)return;

	//如果后面的瓜的所有重量加起来,都小于m,那么当前方案不合法。
	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;
	// cin >> t;
	while(t--)
	solve();
}
  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值