cai_lw's competitive programming library
 
Loading...
Searching...
No Matches
dary_heap.hpp
1#pragma once
2
3#include <functional>
4#include <vector>
5
6namespace cplib {
7
8namespace impl {
9
10template <typename T, typename Comp = std::less<T>, int D = 8>
11struct DaryHeapNormalImpl {};
12
13} // namespace impl
14
29template <typename T, typename Comp = std::less<T>, int D = 8>
30struct DaryHeap {
31 public:
32 using size_type = std::size_t;
33
34 DaryHeap() : arr_(), comp_() {}
35
37 size_type size() const { return arr_.size(); }
38
40 bool empty() const { return arr_.empty(); }
41
43 const T& top() { return arr_.front(); }
44
50 void push(const T& t) {
51 arr_.push_back(t);
52 sift_up_();
53 }
54
56 void push(T&& t) {
57 arr_.push_back(std::move(t));
58 sift_up_();
59 }
60
63 template <typename... Args>
64 void emplace(Args&&... args) {
65 arr_.emplace_back(std::forward<Args>(args)...);
66 sift_up_();
67 }
68
75 void pop() {
76 arr_.front() = std::move(arr_.back());
77 arr_.pop_back();
78 sift_down_();
79 }
80
81 private:
82 std::vector<T> arr_;
83 Comp comp_;
84
85 void sift_up_() {
86 size_type i = arr_.size() - 1;
87 while (i > 0 && comp_(arr_[i], arr_[(i - 1) / D])) {
88 std::swap(arr_[i], arr_[(i - 1) / D]);
89 i = (i - 1) / D;
90 }
91 }
92
93 void sift_down_() {
94 size_type i = 0;
95 while (i * D + 1 < arr_.size()) {
96 size_type min_child = i * D + 1;
97 for (size_type child = i * D + 2; child < std::min(i * D + (D + 1), arr_.size()); child++) {
98 if (comp_(arr_[child], arr_[min_child])) {
99 min_child = child;
100 }
101 }
102 if (comp_(arr_[min_child], arr_[i])) {
103 std::swap(arr_[min_child], arr_[i]);
104 i = min_child;
105 } else {
106 break;
107 }
108 }
109 }
110};
111
112} // namespace cplib
D-ary heap, slightly faster than binary heap due to less random memory access.
Definition: dary_heap.hpp:30
void pop()
Remove the top element from the heap.
Definition: dary_heap.hpp:75
void push(const T &t)
Insert an element into the heap.
Definition: dary_heap.hpp:50
bool empty() const
Returns whether the heap is empty.
Definition: dary_heap.hpp:40
size_type size() const
Returns the number of elements.
Definition: dary_heap.hpp:37
void push(T &&t)
Insert an element into the heap.
Definition: dary_heap.hpp:56
const T & top()
Returns the top element.
Definition: dary_heap.hpp:43
void emplace(Args &&... args)
Construct a new element in place in the heap.
Definition: dary_heap.hpp:64