limited_heap.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. #include <util/generic/queue.h>
  3. #include <util/generic/algorithm.h>
  4. template <class T, class TComparator = TGreater<T>>
  5. class TLimitedHeap {
  6. private:
  7. size_t MaxSize;
  8. TComparator Comparer;
  9. TPriorityQueue<T, TVector<T>, TComparator> Internal;
  10. public:
  11. TLimitedHeap(size_t maxSize, const TComparator& comp = TComparator())
  12. : MaxSize(maxSize)
  13. , Comparer(comp)
  14. , Internal(Comparer)
  15. {
  16. Y_ASSERT(maxSize >= 1);
  17. }
  18. const T& GetMin() const {
  19. return Internal.top();
  20. }
  21. void PopMin() {
  22. Internal.pop();
  23. }
  24. bool Insert(const T& value) {
  25. if (GetSize() == MaxSize) {
  26. if (Comparer(GetMin(), value)) {
  27. return false;
  28. } else {
  29. PopMin();
  30. }
  31. }
  32. Internal.push(value);
  33. return true;
  34. }
  35. bool IsEmpty() const {
  36. return Internal.empty();
  37. }
  38. size_t GetSize() const {
  39. return Internal.size();
  40. }
  41. size_t GetMaxSize() const {
  42. return MaxSize;
  43. }
  44. void SetMaxSize(size_t newMaxSize) {
  45. while (GetSize() > newMaxSize) {
  46. PopMin();
  47. }
  48. MaxSize = newMaxSize;
  49. }
  50. };