【DFS】(选不选)蓝桥杯第十四届-买瓜

cpp 复制代码
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=35,INF=0x3f3f3f3f;
LL p[N];
LL a[N];
int n;
LL m;
int ans=INF;
void dfs(int u,LL sum,int cnt){
	if(sum==m){
		ans=min(ans,cnt);
		return ;
	}
	if(cnt>=ans||u>n||sum+p[u]<m||sum>m) return ;
	dfs(u+1,sum+a[u],cnt);
	dfs(u+1,sum+a[u]/2,cnt+1);
	dfs(u+1,sum,cnt);
}
int main(){
	cin>>n>>m;
	m*=2;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		a[i]*=2;
	}
	sort(a+1,a+1+n,greater<int>());
	for(int i=n;i>=1;i--) p[i]=p[i+1]+a[i];
	dfs(1,0,0);
	if(ans==INF) cout<<"-1"<<endl;
	else cout<<ans<<endl;
	return 0;
}
相关推荐
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:扫描线与线段树求矩形面积并解析
c++·python·算法·bfs·信息学竞赛
电科_银尘1 小时前
【大模型算法与工程 09】SGD、Momentum与AdamW:优化器如何选择
人工智能·算法
货拉拉技术3 小时前
视觉底座:货拉拉OCR的进阶之路
算法
__underline__3 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法
风落青芜5 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
Pniubi9 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
罗西的思考20 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
kyle~1 天前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯1 天前
cpp算法之哈希
c++·算法·哈希算法