P1094 [NOIP 2007 普及组] 纪念品分组 - 洛谷
这道题我们的贪心策略就是每次找出最大的和最小的,如果他们加起来不超过我们给的值,就分成一组,如果超过了,就把大的单独成一组,小的待定
#include <iostream>
#include <algorithm>
typedef long long LL;
using namespace std;
LL w,n;
const int N = 3e4+10;
LL a[N];
int main()
{
cin >> w >> n;
for(int i = 1;i<=n;i++) cin >> a[i];
sort(a+1,a+1+n);
LL l = 1,r = n;
LL ret = 0;
while(l<=r)
{
if(a[l]+a[r] <= w)
{
ret++;l++,r--;
}
else{
ret++;r--;
}
}
cout << ret << endl;
return 0;
}