【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;
}
相关推荐
政企项目老覃16 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水16 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR16 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵17 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽17 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil20817 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民19 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean210320 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil20820 小时前
leetcode 78子集
数据结构·算法·leetcode