小根堆模拟一下即可
cppclass Solution {
public:
long long pickGifts(vector<int>& gifts, int k) {
std::priority_queue<int> pq; // 使用大顶堆存储礼物数量
<!-- more -->
for (int gift : gifts) {
pq.push(gift);
}
while (k-- > 0) {
int maxGifts = pq.top(); // 获取当前剩余礼物数量最多的堆
pq.pop();
if (maxGifts == 0) {
break; // 如果最大礼物数量为0,提前结束
}
int take = static_cast<int>(std::sqrt(maxGifts)); // 取走礼物的数量为平方根(向下取整)
pq.push(take); // 将剩余的礼物数量重新放入堆中
//k--;
}
long long remaining = 0;
while (!pq.empty()) {
remaining += pq.top();
pq.pop();
}
return remaining;
}
};
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!