41 : size_(0), less_(comp) {
52 position_.resize(n, 0);
56 int Size()
const {
return size_; }
57 bool IsEmpty()
const {
return size_ == 0; }
63 position_.assign(position_.size(), 0);
71 void Add(Element element) {
73 SetAndIncreasePriority(++size_, element);
78 Element
Top()
const {
return heap_[1]; }
81 position_[
Top().Index()] = 0;
82 const int old_size = size_--;
83 if (old_size > 1) SetAndDecreasePriority(1, heap_[old_size]);
90 const int to_replace = position_[
index];
92 const int old_size = size_--;
93 if (to_replace == old_size)
return;
94 const Element element = heap_[old_size];
95 if (less_(element, heap_[to_replace])) {
96 SetAndDecreasePriority(to_replace, element);
98 SetAndIncreasePriority(to_replace, element);
107 const int i = position_[element.Index()];
108 if (i > 1 && less_(heap_[i >> 1], element)) {
109 SetAndIncreasePriority(i, element);
111 SetAndDecreasePriority(i, element);
117 SetAndIncreasePriority(position_[element.Index()], element);
120 SetAndDecreasePriority(position_[element.Index()], element);
132 void Set(
int i, Element element) {
134 position_[element.Index()] = i;
140 void SetAndDecreasePriority(
int i,
const Element element) {
141 const int size = size_;
143 const int left = i * 2;
144 const int right = left + 1;
146 if (left >
size)
break;
147 const Element left_element = heap_[left];
148 if (!less_(element, left_element))
break;
149 Set(i, left_element);
153 const Element left_element = heap_[left];
154 const Element right_element = heap_[right];
155 if (less_(left_element, right_element)) {
156 if (!less_(element, right_element))
break;
157 Set(i, right_element);
160 if (!less_(element, left_element))
break;
161 Set(i, left_element);
171 void SetAndIncreasePriority(
int i,
const Element element) {
173 const int parent =
i >> 1;
174 const Element parent_element = heap_[parent];
175 if (!less_(parent_element, element))
break;
176 Set(i, parent_element);
184 std::vector<Element> heap_;
185 std::vector<int> position_;