-
Notifications
You must be signed in to change notification settings - Fork 1
/
priority_queue.rkt
37 lines (28 loc) · 901 Bytes
/
priority_queue.rkt
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
#lang racket
(require "heap.rkt")
(provide make-pqueue pqueue-push! pqueue-pop! pqueue-decrease-key! pqueue-count
set-node-key! node-key)
;; priority queue (smallest priority first)
(struct node ([key #:mutable] [index #:mutable #:auto])
#:methods gen:custom-write
[(define (write-proc node port mode)
(fprintf port "(pq-node ~a)" (node-key node)))])
(define (make-node<=? <=?)
(lambda (x y)
(<=? (node-key x) (node-key y))))
(define (notify-node n index)
(set-node-index! n index))
(define (make-pqueue <=? [init '()])
(list->heap (make-node<=? <=?) init notify-node))
(define (pqueue-push! q key)
(let ([n (node key)])
(heap-add! q n)
n))
(define (pqueue-pop! q)
(let ([ret (heap-min q)])
(heap-remove-min! q)
(node-key ret)))
(define (pqueue-decrease-key! q node)
(heap-decrease-key q (node-index node)))
(define (pqueue-count q)
(heap-count q))