Use C # to implement priority queue
Priority queue is an important data structure. I often use ACM for questions. C ++ STL includes priority_queue. Java also has the PriorityQueue class. Unfortunately, Priority Queues are not included in. NET Framework Base Class Library. Therefore, I had to write one myself in C #, as shown below:
Using System; using System. Collections. Generic; namespace Skyiv. Util {class PriorityQueue
{IComparer
Comparer; T [] heap; public int Count {get; private set;} public PriorityQueue (): this (null) {} public PriorityQueue (int capacity): this (capacity, null) {} public PriorityQueue (IComparer
Comparer): this (16, comparer) {} public PriorityQueue (int capacity, IComparer
Comparer) {this. comparer = (comparer = null )? Comparer
. Default: comparer; this. heap = new T [capacity];} public void Push (T v) {if (Count> = heap. length) Array. resize (ref heap, Count * 2); heap [Count] = v; SiftUp (Count ++);} public T Pop () {var v = Top (); heap [0] = heap [-- Count]; if (Count> 0) SiftDown (0); return v;} public T Top () {if (Count> 0) return heap [0]; throw new InvalidOperationException (the priority queue is empty);} void SiftUp (int n) {var v = heap [n]; for (var n2 = n/2; n> 0 & comparer. compare (v, heap [n2])> 0; n = n2, n2/= 2) heap [n] = heap [n2]; heap [n] = v ;} void SiftDown (int n) {var v = heap [n]; for (var n2 = n * 2; n2 <Count; n = n2, n2 * = 2) {if (n2 + 1 <Count & comparer. compare (heap [n2 + 1], heap [n2])> 0) n2 ++; if (comparer. compare (v, heap [n2])> = 0) break; heap [n] = heap [n2];} heap [n] = v ;}}}
As shown abovePriorityQueue The generic class provides four common constructor functions. The first one is a constructor without parameters. The remaining constructor allows you to specify the number of initial elements (capacity) included in the priority queue), how to compare keys (comparer ).
This program uses heap to implement priority queues. Therefore, the required space is the smallest. The time complexity of the Count attribute and the Top method is O (1), while that of the Push and Pop methods is O (logN ).
I used List The generic class has implemented A priority queue. Please refer to my blog Timus1016. A Cube on the Walk. Although it is simpler, there are only 23 lines of program code, but the efficiency is not high. the time complexity of the Push and Pop methods is O (N ).