static int speed_up = []() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
vector<int> hash(30001, 0);
int i = 1, j, size = people.size();
for (i = 1; i <= size; i++) hash[people[i - 1]]++;
int res = 0;
for (i = limit; i >= 1; i--) {
if (hash[i] == 0) continue;
int max_w = limit - i;
if (max_w == 0) {
res += hash[i];
hash[i] = 0;
continue;
}
//尝试寻找最重的能搭载的乘客
if (limit >= i * 2) {
res += hash[i] / 2;
hash[i] %= 2;
if (hash[i] == 0) continue;
}
for (j = min(max_w, i-1); j >= 1; j--) {
if (hash[j] > 0) {
int val = min(hash[j], hash[i]);
hash[i] -= val;
hash[j] -= val;
res += val;
if (hash[i] == 0) break;
}
}
res += hash[i];
hash[i] = 0;
}
return res;
}
};