-
Notifications
You must be signed in to change notification settings - Fork 99
/
PairingHeap.scala
406 lines (349 loc) · 12.8 KB
/
PairingHeap.scala
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* Copyright (c) 2015 Typelevel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package cats.collections
import cats.{Order, Show}
import cats.kernel.CommutativeMonoid
import scala.annotation.tailrec
/**
* A PairingHeap is a heap with excellent empirical performance.
*
* See: https://en.wikipedia.org/wiki/Pairing_heap in particular:
* https://en.wikipedia.org/wiki/Pairing_heap#Summary_of_running_times
*
* Additionally, it supports an efficient O(1) combine operation
*/
sealed abstract class PairingHeap[A] {
import PairingHeap._
/**
* insert an item into the heap O(1)
*/
def add(x: A)(implicit order: Order[A]): PairingHeap[A] =
if (this.isEmpty) apply(x)
else {
val thisTree = this.asInstanceOf[Tree[A]]
if (order.lt(x, thisTree.min)) Tree(x, this :: Nil)
else Tree(thisTree.min, Tree(x, Nil) :: thisTree.subtrees)
}
/*
* Add a collection of items in. This is O(N) if as is size N
*/
def addAll(as: Iterable[A])(implicit order: Order[A]): PairingHeap[A] = {
val ait = as.iterator
var heap = this
while (ait.hasNext) {
heap = heap + ait.next()
}
heap
}
/**
* This is O(N) in the worst case, but we use the heap property to be lazy
*/
def contains(a: A)(implicit order: Order[A]): Boolean =
if (isEmpty) false
else {
val c = order.compare(a, this.asInstanceOf[Tree[A]].min)
if (c < 0) false // a is less than the min
else if (c == 0) true // a == min
else {
@tailrec
def loop(ts: List[PairingHeap[A]]): Boolean =
ts match {
case Nil => false
case h :: tail => h.contains(a) || loop(tail)
}
loop(subtrees)
}
}
/**
* Returns min value on the heap, if it exists
*
* O(1)
*/
def minimumOption: Option[A]
/**
* Returns the size of the heap. O(1)
*/
def size: Long
/**
* Verifies if the heap is empty. O(1)
*/
def isEmpty: Boolean
/**
* Return true if this is not empty O(1)
*/
def nonEmpty: Boolean = !isEmpty
/**
* Returns a sorted list of the elements within the heap. O(N log N)
*/
def toList(implicit order: Order[A]): List[A] = {
@tailrec
def loop(h: PairingHeap[A], acc: List[A]): List[A] =
h match {
case Tree(m, _) => loop(h.remove, m :: acc)
case Leaf() => acc.reverse
}
loop(this, Nil)
}
/**
* Merge two heaps, this is O(1) work
*/
def combine(that: PairingHeap[A])(implicit order: Order[A]): PairingHeap[A]
/**
* Check to see if a predicate is ever true worst case O(N) but stops at the first true
*/
def exists(fn: A => Boolean): Boolean
/**
* Check to see if a predicate is always true worst case O(N) but stops at the first false
*/
def forall(fn: A => Boolean): Boolean
/**
* Aggregate with a commutative monoid, since the Heap is not totally ordered
*/
def unorderedFoldMap[B](fn: A => B)(implicit m: CommutativeMonoid[B]): B =
if (isEmpty) m.empty
else {
val thisTree = this.asInstanceOf[Tree[A]]
m.combine(fn(thisTree.min), m.combineAll(thisTree.subtrees.map(_.unorderedFoldMap(fn))))
}
/**
* Similar to unorderedFoldMap without a transformation
*/
def unorderedFold(implicit m: CommutativeMonoid[A]): A =
if (isEmpty) m.empty
else {
val thisTree = this.asInstanceOf[Tree[A]]
m.combine(thisTree.min, m.combineAll(thisTree.subtrees.map(_.unorderedFold)))
}
/**
* do a foldLeft in the same order as toList. requires an Order[A], which prevents us from making a
* Foldable[PairingHeap] instance.
*
* prefer unorderedFoldMap if you can express your operation as a commutative monoid since it is O(N) vs O(N log N)
* for this method
*/
def foldLeft[B](init: B)(fn: (B, A) => B)(implicit order: Order[A]): B = {
@tailrec
def loop(h: PairingHeap[A], acc: B): B =
h match {
case Tree(m, _) => loop(h.remove, fn(acc, m))
case Leaf() => acc
}
loop(this, init)
}
/**
* Remove the min element from the heap (the root) and return it along with the updated heap. Order O(log n)
*/
def pop(implicit order: Order[A]): Option[(A, PairingHeap[A])] = this match {
case Tree(m, subtrees) => Some((m, combineAll(subtrees)))
case Leaf() => None
}
/**
* if not empty, remove the min, else return empty this is thought to be O(log N) (but not proven to be so)
*/
def remove(implicit order: Order[A]): PairingHeap[A] =
if (isEmpty) this
else {
val thisTree = this.asInstanceOf[Tree[A]]
combineAll(thisTree.subtrees)
}
/**
* Alias for add
*/
def +(x: A)(implicit order: Order[A]): PairingHeap[A] = add(x)
private[collections] def subtrees: List[PairingHeap[A]]
}
object PairingHeap {
def empty[A]: PairingHeap[A] = Leaf()
def apply[A](x: A): PairingHeap[A] = Tree(x, Nil)
/**
* This is thought to be O(log N) where N is the size of the final heap
*/
def combineAll[A: Order](it: Iterable[PairingHeap[A]]): PairingHeap[A] =
combineAllIter(it.iterator, Nil)
@tailrec
private def combineLoop[A: Order](ts: List[PairingHeap[A]], acc: PairingHeap[A]): PairingHeap[A] =
ts match {
case Nil => acc
case h :: tail => combineLoop(tail, h.combine(acc))
}
@tailrec
private def combineAllIter[A: Order](iter: Iterator[PairingHeap[A]], pairs: List[PairingHeap[A]]): PairingHeap[A] =
if (iter.isEmpty) {
combineLoop(pairs, empty[A])
} else {
val p0 = iter.next()
if (iter.isEmpty) combineLoop(pairs, p0)
else {
val p1 = iter.next()
val pair = p0.combine(p1) // this is where the name pairing heap comes from
combineAllIter(iter, pair :: pairs)
}
}
/**
* build a heap from a list of items, O(N)
*/
def fromIterable[A](as: Iterable[A])(implicit order: Order[A]): PairingHeap[A] = {
val iter = as.iterator
var heap = empty[A]
while (iter.hasNext) {
heap = heap + iter.next()
}
heap
}
/**
* this is useful for finding the k maximum values in O(N) times for N items same as
* as.toList.sorted.reverse.take(count), but O(N log(count)) vs O(N log N) for a full sort. When N is very large, this
* can be a very large savings
*/
def takeLargest[A](as: Iterable[A], count: Int)(implicit order: Order[A]): PairingHeap[A] =
if (count <= 0) empty
else {
var heap = empty[A]
val iter = as.iterator
while (iter.hasNext) {
val a = iter.next()
heap =
if (heap.size < count) heap + a
else if (order.lt(heap.asInstanceOf[Tree[A]].min, a)) heap.remove + a
else heap
}
heap
}
final private[collections] case class Tree[A](min: A, subtrees: List[PairingHeap[A]]) extends PairingHeap[A] {
override val size = {
@tailrec
def loop(ts: List[PairingHeap[A]], acc: Long): Long =
ts match {
case Nil => acc
case h :: tail => loop(tail, acc + h.size)
}
loop(subtrees, 1L)
}
override def isEmpty: Boolean = false
override def minimumOption: Option[A] = Some(min)
override def exists(fn: A => Boolean): Boolean =
fn(min) || {
@tailrec
def loop(hs: List[PairingHeap[A]]): Boolean =
hs match {
case h :: tail => h.exists(fn) || loop(tail)
case Nil => false
}
loop(subtrees)
}
override def forall(fn: A => Boolean): Boolean =
fn(min) && {
@tailrec
def loop(hs: List[PairingHeap[A]]): Boolean =
hs match {
case h :: tail => h.forall(fn) && loop(tail)
case Nil => true
}
loop(subtrees)
}
override def combine(that: PairingHeap[A])(implicit order: Order[A]): PairingHeap[A] =
if (that.isEmpty) this
else {
val thatTree = that.asInstanceOf[Tree[A]]
if (order.lt(min, thatTree.min)) Tree(min, that :: subtrees)
else Tree(thatTree.min, this :: thatTree.subtrees)
}
}
final private case object Leaf extends PairingHeap[Nothing] {
def apply[A](): PairingHeap[A] = this.asInstanceOf[PairingHeap[A]]
def unapply[A](heap: PairingHeap[A]): Boolean = heap.isEmpty
override def subtrees: List[PairingHeap[Nothing]] = Nil
override def size: Long = 0L
override def isEmpty: Boolean = true
override def minimumOption: Option[Nothing] = None
override def exists(fn: Nothing => Boolean): Boolean = false
override def forall(fn: Nothing => Boolean): Boolean = true
override def combine(that: PairingHeap[Nothing])(implicit order: Order[Nothing]): PairingHeap[Nothing] = that
}
implicit def toShowable[A](implicit s: Show[A], order: Order[A]): Show[PairingHeap[A]] = new Show[PairingHeap[A]] {
override def show(f: PairingHeap[A]): String = {
val sb = new java.lang.StringBuilder
sb.append("PairingHeap(")
f.foldLeft(false) { (notFirst, a) =>
if (notFirst) sb.append(", ")
sb.append(s.show(a))
true
}
sb.append(")")
sb.toString
}
}
implicit val catsCollectionPairingHeapPartiallyOrderedSet: PartiallyOrderedSet[PairingHeap] =
new PartiallyOrderedSet[PairingHeap] {
def unorderedFoldMap[A, B: CommutativeMonoid](ha: PairingHeap[A])(fn: A => B): B =
ha.unorderedFoldMap(fn)
override def unorderedFold[A: CommutativeMonoid](ha: PairingHeap[A]): A =
ha.unorderedFold
override def isEmpty[A](h: PairingHeap[A]) = h.isEmpty
override def nonEmpty[A](h: PairingHeap[A]) = h.nonEmpty
override def exists[A](ha: PairingHeap[A])(fn: A => Boolean) = ha.exists(fn)
override def forall[A](ha: PairingHeap[A])(fn: A => Boolean) = ha.forall(fn)
override def size[A](h: PairingHeap[A]) = h.size
// PartiallyOrderedSet methods
override def add[A](fa: PairingHeap[A], a: A)(implicit order: Order[A]): PairingHeap[A] =
fa.add(a)
override def addAll[A: Order](fa: PairingHeap[A], as: Iterable[A]): PairingHeap[A] =
fa.addAll(as)
override def contains[A](fa: PairingHeap[A], a: A)(implicit order: Order[A]): Boolean =
fa.contains(a)
override def build[A](as: Iterable[A])(implicit order: Order[A]): PairingHeap[A] =
PairingHeap.fromIterable(as)
override def empty[A]: PairingHeap[A] = PairingHeap.empty[A]
override def minimumOption[A](fa: PairingHeap[A]): Option[A] = fa.minimumOption
override def removeMin[A](fa: PairingHeap[A])(implicit order: Order[A]): PairingHeap[A] = fa.remove
override def singleton[A](a: A): PairingHeap[A] = PairingHeap(a)
override def toSortedList[A: Order](fa: PairingHeap[A]): List[A] =
fa.toList
override def sortedFoldLeft[A: Order, B](fa: PairingHeap[A], init: B)(fn: (B, A) => B): B =
fa.foldLeft(init)(fn)
override def order[A: Order] = new PairingHeapOrder[A]
}
private[collections] class PairingHeapOrder[A](implicit ordA: Order[A]) extends Order[PairingHeap[A]] {
@tailrec
final def compare(left: PairingHeap[A], right: PairingHeap[A]): Int =
if (left.isEmpty) {
if (right.isEmpty) 0
else -1
} else if (right.isEmpty) 1
else {
val lt = left.asInstanceOf[Tree[A]]
val rt = right.asInstanceOf[Tree[A]]
val c = ordA.compare(lt.min, rt.min)
if (c != 0) c
else compare(left.remove, right.remove)
}
}
/**
* This is the same order as you would get by doing `.toList` and ordering by that
*/
implicit def catsCollectionPairingHeapOrder[A: Order]: Order[PairingHeap[A]] =
new PairingHeapOrder[A]
implicit def catsCollectionPairingHeapCommutativeMonoid[A: Order]: CommutativeMonoid[PairingHeap[A]] =
new CommutativeMonoid[PairingHeap[A]] {
def empty = PairingHeap.empty[A]
def combine(a: PairingHeap[A], b: PairingHeap[A]) = a.combine(b)
}
}