Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BLI_inplace_priority_queue.hh « blenlib « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 29821330f9b5210614cb9b248262c3c8f1730073 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/* SPDX-License-Identifier: GPL-2.0-or-later */

#pragma once

#include "BLI_array.hh"
#include "BLI_dot_export.hh"

namespace blender {

/**
 * An InplacePriorityQueue adds priority queue functionality to an existing array. The underlying
 * array is not changed. Instead, the priority queue maintains indices into the original array.
 *
 * The priority queue provides efficient access to the element in order of their priorities.
 *
 * When a priority changes, the priority queue has to be informed using one of the following
 * methods: #priority_decreased, #priority_increased or #priority_changed.
 */
template<
    /* Type of the elements in the underlying array. */
    typename T,
    /* Binary function that takes two `const T &` inputs and returns true,
     * when the first input has greater priority than the second. */
    typename FirstHasHigherPriority = std::greater<T>>
class InplacePriorityQueue {
 private:
  /* Underlying array the priority queue is built upon. This is a span instead of a mutable span,
   * because this data structure never changes the values itself. */
  Span<T> data_;
  /* Maps indices from the heap (binary tree in array format) to indices of the underlying/original
   * array. */
  Array<int64_t> heap_to_orig_;
  /* This is the inversion of the above mapping. */
  Array<int64_t> orig_to_heap_;
  /* Number of elements that are currently in the priority queue. */
  int64_t heap_size_ = 0;
  /* Function that can be changed to customize how the priority of two elements is compared. */
  FirstHasHigherPriority first_has_higher_priority_fn_;

 public:
  /**
   * Construct the priority queue on top of the data in the given span.
   */
  InplacePriorityQueue(Span<T> data)
      : data_(data), heap_to_orig_(data_.size()), orig_to_heap_(data_.size())
  {
    for (const int64_t i : IndexRange(data_.size())) {
      heap_to_orig_[i] = i;
      orig_to_heap_[i] = i;
    }

    this->rebuild();
  }

  /**
   * Rebuilds the priority queue from the array that has been passed to the constructor.
   */
  void rebuild()
  {
    const int final_heap_size = data_.size();
    if (final_heap_size > 1) {
      for (int64_t i = this->get_parent(final_heap_size - 1); i >= 0; i--) {
        this->heapify(i, final_heap_size);
      }
    }
    heap_size_ = final_heap_size;
  }

  /**
   * Returns the number of elements in the priority queue.
   * This is less or equal than the size of the underlying array.
   */
  int64_t size() const
  {
    return heap_size_;
  }

  /**
   * Returns true, when the priority queue contains no elements. If this returns true, #peek and
   * #pop must not be used.
   */
  bool is_empty() const
  {
    return heap_size_ == 0;
  }

  /**
   * Get the element with the highest priority in the priority queue.
   * The returned reference is const, because the priority queue has read-only access to the
   * underlying data. If you need a mutable reference, use #peek_index instead.
   */
  const T &peek() const
  {
    return data_[this->peek_index()];
  }

  /**
   * Get the element with the highest priority in the priority queue and remove it.
   * The returned reference is const, because the priority queue has read-only access to the
   * underlying data. If you need a mutable reference, use #pop_index instead.
   */
  const T &pop()
  {
    return data_[this->pop_index()];
  }

  /**
   * Get the index of the element with the highest priority in the priority queue.
   */
  int64_t peek_index() const
  {
    BLI_assert(!this->is_empty());
    return heap_to_orig_[0];
  }

  /**
   * Get the index of the element with the highest priority in the priority queue and remove it.
   */
  int64_t pop_index()
  {
    BLI_assert(!this->is_empty());
    const int64_t top_index_orig = heap_to_orig_[0];
    heap_size_--;
    if (heap_size_ > 1) {
      this->swap_indices(0, heap_size_);
      this->heapify(0, heap_size_);
    }
    return top_index_orig;
  }

  /**
   * Inform the priority queue that the priority of the element at the given index has been
   * decreased.
   */
  void priority_decreased(const int64_t index)
  {
    const int64_t heap_index = orig_to_heap_[index];
    if (heap_index >= heap_size_) {
      /* This element is not in the queue currently. */
      return;
    }
    this->heapify(heap_index, heap_size_);
  }

  /**
   * Inform the priority queue that the priority of the element at the given index has been
   * increased.
   */
  void priority_increased(const int64_t index)
  {
    int64_t current = orig_to_heap_[index];
    if (current >= heap_size_) {
      /* This element is not in the queue currently. */
      return;
    }
    while (true) {
      if (current == 0) {
        break;
      }
      const int64_t parent = this->get_parent(current);
      if (this->first_has_higher_priority(parent, current)) {
        break;
      }
      this->swap_indices(current, parent);
      current = parent;
    }
  }

  /**
   * Inform the priority queue that the priority of the element at the given index has been
   * changed.
   */
  void priority_changed(const int64_t index)
  {
    this->priority_increased(index);
    this->priority_decreased(index);
  }

  /**
   * Returns the indices of all elements that are in the priority queue.
   * There are no guarantees about the order of indices.
   */
  Span<int64_t> active_indices() const
  {
    return heap_to_orig_.as_span().take_front(heap_size_);
  }

  /**
   * Returns the indices of all elements that are not in the priority queue.
   * The indices are in reverse order of their removal from the queue.
   * I.e. the index that has been removed last, comes first.
   */
  Span<int64_t> inactive_indices() const
  {
    return heap_to_orig_.as_span().drop_front(heap_size_);
  }

  /**
   * Returns the concatenation of the active and inactive indices.
   */
  Span<int64_t> all_indices() const
  {
    return heap_to_orig_;
  }

  /**
   * Return the heap used by the priority queue as dot graph string.
   * This exists for debugging purposes.
   */
  std::string to_dot() const
  {
    return this->partial_to_dot(heap_size_);
  }

 private:
  bool first_has_higher_priority(const int64_t a, const int64_t b)
  {
    const T &value_a = data_[heap_to_orig_[a]];
    const T &value_b = data_[heap_to_orig_[b]];
    return first_has_higher_priority_fn_(value_a, value_b);
  }

  void swap_indices(const int64_t a, const int64_t b)
  {
    std::swap(heap_to_orig_[a], heap_to_orig_[b]);
    orig_to_heap_[heap_to_orig_[a]] = a;
    orig_to_heap_[heap_to_orig_[b]] = b;
  }

  void heapify(const int64_t parent, const int64_t heap_size)
  {
    int64_t max_index = parent;
    const int left = this->get_left(parent);
    const int right = this->get_right(parent);
    if (left < heap_size && this->first_has_higher_priority(left, max_index)) {
      max_index = left;
    }
    if (right < heap_size && this->first_has_higher_priority(right, max_index)) {
      max_index = right;
    }
    if (max_index != parent) {
      this->swap_indices(parent, max_index);
      this->heapify(max_index, heap_size);
    }
    if (left < heap_size) {
      BLI_assert(!this->first_has_higher_priority(left, parent));
    }
    if (right < heap_size) {
      BLI_assert(!this->first_has_higher_priority(right, parent));
    }
  }

  int64_t get_parent(const int64_t child) const
  {
    BLI_assert(child > 0);
    return (child - 1) / 2;
  }

  int64_t get_left(const int64_t parent) const
  {
    return parent * 2 + 1;
  }

  int64_t get_right(const int64_t parent) const
  {
    return parent * 2 + 2;
  }

  std::string partial_to_dot(const int size) const
  {
    dot::DirectedGraph digraph;
    Array<dot::Node *> dot_nodes(size);
    for (const int i : IndexRange(size)) {
      std::stringstream ss;
      ss << data_[heap_to_orig_[i]];
      const std::string name = ss.str();
      dot::Node &node = digraph.new_node(name);
      node.set_shape(dot::Attr_shape::Rectangle);
      node.attributes.set("ordering", "out");
      dot_nodes[i] = &node;
      if (i > 0) {
        const int64_t parent = this->get_parent(i);
        digraph.new_edge(*dot_nodes[parent], node);
      }
    }
    return digraph.to_dot_string();
  }
};

}  // namespace blender