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);
67 bool Contains(
int index)
const {
return position_[index] != 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);
124 Element
GetElement(
int index)
const {
return heap_[position_[index]]; }
132 void Set(Element* heap,
int i, Element element) {
134 position_[element.Index()] = i;
140 void SetAndDecreasePriority(
int i,
const Element element) {
141 const int size = size_;
142 Element* heap = heap_.data();
144 const int left = i * 2;
145 const int right = left + 1;
147 if (left > size)
break;
148 const Element left_element = heap[left];
149 if (!less_(element, left_element))
break;
150 Set(heap, i, left_element);
154 const Element left_element = heap[left];
155 const Element right_element = heap[right];
156 if (less_(left_element, right_element)) {
157 if (!less_(element, right_element))
break;
158 Set(heap, i, right_element);
161 if (!less_(element, left_element))
break;
162 Set(heap, i, left_element);
166 Set(heap, i, element);
172 void SetAndIncreasePriority(
int i,
const Element element) {
173 Element* heap = heap_.data();
175 const int parent =
i >> 1;
176 const Element parent_element = heap[parent];
177 if (!less_(parent_element, element))
break;
178 Set(heap, i, parent_element);
181 Set(heap, i, element);
186 std::vector<Element> heap_;
187 std::vector<int> position_;