独木舟|贪心
2026-04-03 19:17:42
发布于:河北
5阅读
0回复
0点赞
废话少说,上代码
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
// 取消cin/cout与stdio的同步,提高输入输出效率
ios::sync_with_stdio(false);
// 解除cin与cout的绑定,进一步优化性能
cin.tie(nullptr);
cout.tie(nullptr);
// w: 载重限制, n: 旅行人数, t[]: 存储每个人的重量, cnt: 记录独木舟数量, left: 左指针
int w=0,n=0,t[30001]={0},cnt=0,left=0;
cin>>w>>n; // 输入载重限制和物品数量
// 输入每个物品的重量
for(int i=0;i<n;++i)
cin>>t[i];
// 将人按重量从小到大排序,便于使用贪心策略
sort(t,t+n);
// 使用双指针法,right从最大重量开始向左移动
for(int right=n-1;right>=left;--right){
// 如果最轻的人和当前最重的人能一起坐独木舟
if(t[left]+t[right]<=w){
cnt++; // 独木舟数量加1
left++; // 最轻人已运输,左指针右移
}else{
// 当前最重人只能单独坐独木舟
cnt++;
}
}
cout<<cnt; // 输出最少独木舟数量
return 0;
}
这里空空如也








有帮助,赞一个