书架|贪心
2026-04-04 12:28:32
发布于:河北
5阅读
0回复
0点赞
废话少说,上代码
#include<iostream>
#include<algorithm>
using namespace std;
// 比较函数,用于降序排序
bool cmp(int a,int b){
return a>b;
}
int main(){
// 提高输入输出速度
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// n: 🐄数量, b: 需要达到的高度, h[]: 存储🐄高度的数组
// sum: 当前累计高度, cnt: 使用的🐄数量
int n=0,b=0,h[20001]={0},sum=0,cnt=0;
// 输入🐄数量和目标高度
cin>>n>>b;
// 输入每个🐄的高度
for(int i=0;i<n;++i)
cin>>h[i];
// 将🐄高度按降序排列(从大到小)
sort(h,h+n,cmp);
// 贪心算法:优先选择较高的🐄
for(int i=0;i<n;++i){
if(sum>=b) break; // 如果当前累计高度已达到目标,则退出循环
else{
sum+=h[i]; // 累加当前🐄高度
cnt++; // 增加使用的🐄数量
}
}
// 输出最少需要多少个🐄才能达到或超过目标高度
cout<<cnt;
return 0;
}
这里空空如也








有帮助,赞一个