这题算贪心中最简单的,属于背包问题吧,写的效率有点低,用数组加指针控制应该更好。
#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; }