编辑
2023-10-29
数据结构与算法
00
请注意,本文编写于 607 天前,最后修改于 607 天前,其中某些信息可能已经过时。

image.png

小根堆模拟一下即可

cpp
class 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 许可协议。转载请注明出处!