当前位置:   article > 正文

蓝桥杯真题讲解:买瓜 (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();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/489385
推荐阅读
相关标签
  

闽ICP备14008679号