UVa 1149 - Bin Packing [贪心]

这题算贪心中最简单的,属于背包问题吧,写的效率有点低,用数组加指针控制应该更好。

#include <iostream>
#include <deque>
#include <iterator>
#include <functional>
#include <algorithm>
using namespace std;

int main()
{
    int T; cin >> T;
    while(T--){
        deque<int> a;
        int n, k; cin >> n >> k;
        for(int i = 0; i < n; ++i){
            int t; cin >> t;
            a.push_back(t);
        }
        sort(a.begin(), a.end(), greater<int>());
        int cnt = 0;
        while(!a.empty()){
            ++cnt;
            //copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
            //cout << endl;
            if(a.size()>=2){
                int x = a.front(); a.pop_front();
                deque<int>::iterator it = lower_bound(a.begin(), a.end(), k - x, greater<int>());
                if(it != a.end()) a.erase(it);
            }
            else a.pop_back();
        }
        cout << cnt << endl;
        if(T) cout << endl;
    }
    return 0;
}


posted @ 2015-03-13 17:23  Popco  阅读(108)  评论(0编辑  收藏  举报