-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.php
More file actions
311 lines (268 loc) · 6.71 KB
/
Copy pathPriorityQueue.php
File metadata and controls
311 lines (268 loc) · 6.71 KB
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<?php
declare(strict_types=1);
/*
* This file is part of the univeros/framework
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Altair\Structure;
use Altair\Structure\Contracts\CollectionInterface;
use Altair\Structure\Traits\CollectionTrait;
use Altair\Structure\Traits\SquaredCapacityTrait;
use Generator;
use IteratorAggregate;
use Override;
use ReturnTypeWillChange;
use UnderflowException;
/**
*
* PriorityQueue.
*
* A PriorityQueue is very similar to a Queue. Values are pushed into the queue with an assigned priority, and the
* value with the highest priority will always be at the front of the queue. Iterating over a PriorityQueue is
* destructive, equivalent to successive pop operations until the queue is empty. Implemented using a max heap.
*
* @link https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd#.gl62k1xqr
*
* @template TValue
*
* @implements CollectionInterface<int, TValue>
* @implements IteratorAggregate<int, TValue>
*
* @phpstan-consistent-constructor
*/
class PriorityQueue implements IteratorAggregate, CollectionInterface
{
/** @use CollectionTrait<int, TValue> */
use CollectionTrait;
use SquaredCapacityTrait;
/**
* Typed against the concrete PriorityNode (not the interface) so its public
* $value/$priority/$stamp properties resolve; the queue only ever stores
* PriorityNode instances.
*
* @var array<int, PriorityNode<TValue>>
*/
protected $heap = [];
/**
* @var int
*/
protected $stamp = 0;
/**
* Initializes a new priority queue.
*
* @param array<int, PriorityNode<TValue>>|null $heap
* @param int|null $stamp
*/
public function __construct($heap = [], $stamp = 0)
{
$this->heap = $heap ?? [];
$this->stamp = $stamp ?? 0;
}
/**
* {@inheritDoc}
*
* @return self<TValue>
*/
#[Override]
public function copy(): PriorityQueue
{
return new PriorityQueue($this->heap, $this->capacity);
}
/**
* {@inheritDoc}
*/
#[ReturnTypeWillChange]
#[Override]
public function count(): int
{
return \count($this->heap);
}
/**
* Returns the value with the highest priority without removing it.
*
* @return TValue
*/
public function peek()
{
if ($this->isEmpty()) {
throw new UnderflowException('Queue is empty');
}
return $this->heap[0]->value;
}
/**
* Returns and removes the value with the highest priority in the queue.
*
* @return TValue
*/
public function pop()
{
if ($this->heap === []) {
throw new UnderflowException('Queue is empty');
}
// Last leaf of the heap to become the new root.
$leaf = array_pop($this->heap);
if ($this->heap === []) {
return $leaf->value;
}
// Cache the current root value to return before replacing with next.
$value = $this->getRoot()->value;
// Replace the root, then sift down.
$this->setRoot($leaf);
$this->siftDown(0);
$this->adjustCapacity();
return $value;
}
/**
* Pushes a value into the queue, with a specified priority.
*
* @param TValue $value
*/
public function push(mixed $value, int $priority): void
{
$this->adjustCapacity();
// Add new leaf, then sift up to maintain heap,
$this->heap[] = new PriorityNode($value, $priority, $this->stamp++);
$this->siftUp(\count($this->heap) - 1);
}
/**
* {@inheritDoc}
*
* @return array<int, TValue>
*/
#[Override]
public function toArray(): array
{
$heap = $this->heap;
$array = [];
while (!$this->isEmpty()) {
$array[] = $this->pop();
}
$this->heap = $heap;
return $array;
}
/**
* Get iterator.
*
* @return Generator<int, TValue>
*/
#[ReturnTypeWillChange]
#[Override]
public function getIterator()
{
while (!$this->isEmpty()) {
yield $this->pop();
}
}
/**
* Left.
*
*
*/
protected function left(int $index): int
{
return ($index * 2) + 1;
}
/**
* Right.
*
*
*/
protected function right(int $index): int
{
return ($index * 2) + 2;
}
/**
* Parent.
*
*
*/
protected function parent(int $index): int
{
return (int) (($index - 1) / 2);
}
/**
* Compare.
*
*
*/
protected function compare(int $a, int $b): int
{
$x = $this->heap[$a];
$y = $this->heap[$b];
// Compare priority, using insertion stamp as fallback.
return ($x->priority <=> $y->priority) ?: ($y->stamp <=> $x->stamp);
}
/**
* Swap.
*/
protected function swap(int $a, int $b): void
{
$temp = $this->heap[$a];
$this->heap[$a] = $this->heap[$b];
$this->heap[$b] = $temp;
}
/**
* Get Largest Leaf.
*
*
*/
protected function getLargestLeaf(int $parent): int
{
$left = $this->left($parent);
$right = $this->right($parent);
if ($right < \count($this->heap) && $this->compare($left, $right) < 0) {
return $right;
}
return $left;
}
/**
* Sift Up.
*/
protected function siftUp(int $leaf): void
{
for (; $leaf > 0; $leaf = $parent) {
$parent = $this->parent($leaf);
// Done when parent priority is greater.
if ($this->compare($leaf, $parent) < 0) {
break;
}
$this->swap($parent, $leaf);
}
}
/**
* Set Root.
*
* @param PriorityNode<TValue> $node
*/
protected function setRoot(PriorityNode $node): void
{
$this->heap[0] = $node;
}
/**
* Get Root.
*
* @return PriorityNode<TValue>
*/
protected function getRoot(): PriorityNode
{
return $this->heap[0];
}
/**
* Sift Down.
*/
private function siftDown(int $node): void
{
$last = floor(\count($this->heap) / 2);
for ($parent = $node; $parent < $last; $parent = $leaf) {
// Determine the largest leaf to potentially swap with the parent.
$leaf = $this->getLargestLeaf($parent);
// Done if the parent is not greater than its largest leaf
if ($this->compare($parent, $leaf) > 0) {
break;
}
$this->swap($parent, $leaf);
}
}
}