洛谷 P1094 [NOIP 2007 普及组] 纪念品分组

显而易见贪心算法,升序排序后双指针移动判定即可。

AcCode:

#include<iostream>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
vector<int> v;
int main(){
    int U, N, ans = 0;
    cin >> U >> N;
    while(N--){
        int x;
        cin >> x;
        v.push_back(x);
    }
    sort(v.begin(), v.end());
    int f = 0, b = v.size() - 1;
    while(f <= b){
        if(v[f] + v[b] <= U) ans++, f++, b--;
        else ans++, b--;
    }
    cout << ans;
    return 0;
}
posted @ 2025-05-09 00:18  Yuhhhhh  阅读(39)  评论(0)    收藏  举报