P1094 纪念品分组题解

题目传递门

#include <bits/stdc++.h>

using namespace std;
int w, n;
const int N = 30010;
int a[N];
//双指针
int h = 1, t = n, cnt;

int main() {
    cin >> w >> n;
    for (int i = 1; i <= n; i++)cin >> a[i];
    sort(a + 1, a + 1 + n);

    //双指针,太聪明的办法了
    while (h <= t)
        if (a[t] + a[h] > w) cnt++, t--; //装不下的话,a[t]独立成组
        else cnt++, t--, h++;//能装下的话,a[t]+a[h]为一组

    cout << cnt << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15037921.html