GenericPriorityQueue.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. namespace Priority_Queue
  6. {
  7. /// <summary>
  8. /// Credit: https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp
  9. /// A copy of StablePriorityQueue which also has generic priority-type
  10. /// </summary>
  11. /// <typeparam name="TItem">The values in the queue. Must extend the GenericPriorityQueue class</typeparam>
  12. /// <typeparam name="TPriority">The priority-type. Must extend IComparable&lt;TPriority&gt;</typeparam>
  13. public sealed class GenericPriorityQueue<TItem, TPriority> : IFixedSizePriorityQueue<TItem, TPriority>
  14. where TItem : GenericPriorityQueueNode<TPriority>
  15. where TPriority : IComparable<TPriority>
  16. {
  17. private int _numNodes;
  18. private TItem[] _nodes;
  19. private long _numNodesEverEnqueued;
  20. /// <summary>
  21. /// Instantiate a new Priority Queue
  22. /// </summary>
  23. /// <param name="maxNodes">The max nodes ever allowed to be enqueued (going over this will cause undefined behavior)</param>
  24. public GenericPriorityQueue(int maxNodes)
  25. {
  26. #if DEBUG
  27. if (maxNodes <= 0)
  28. {
  29. throw new InvalidOperationException("New queue size cannot be smaller than 1");
  30. }
  31. #endif
  32. _numNodes = 0;
  33. _nodes = new TItem[maxNodes + 1];
  34. _numNodesEverEnqueued = 0;
  35. }
  36. /// <summary>
  37. /// Returns the number of nodes in the queue.
  38. /// O(1)
  39. /// </summary>
  40. public int Count => _numNodes;
  41. /// <summary>
  42. /// Returns the maximum number of items that can be enqueued at once in this queue. Once you hit this number (ie. once Count == MaxSize),
  43. /// attempting to enqueue another item will cause undefined behavior. O(1)
  44. /// </summary>
  45. public int MaxSize => _nodes.Length - 1;
  46. /// <summary>
  47. /// Removes every node from the queue.
  48. /// O(n) (So, don't do this often!)
  49. /// </summary>
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public void Clear()
  52. {
  53. Array.Clear(_nodes, 1, _numNodes);
  54. _numNodes = 0;
  55. }
  56. /// <summary>
  57. /// Returns (in O(1)!) whether the given node is in the queue. O(1)
  58. /// </summary>
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. public bool Contains(TItem node)
  61. {
  62. #if DEBUG
  63. if (node == null)
  64. {
  65. throw new ArgumentNullException(nameof(node));
  66. }
  67. if (node.QueueIndex < 0 || node.QueueIndex >= _nodes.Length)
  68. {
  69. throw new InvalidOperationException("node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?");
  70. }
  71. #endif
  72. return (_nodes[node.QueueIndex] == node);
  73. }
  74. /// <summary>
  75. /// Enqueue a node to the priority queue. Lower values are placed in front. Ties are broken by first-in-first-out.
  76. /// If the queue is full, the result is undefined.
  77. /// If the node is already enqueued, the result is undefined.
  78. /// O(log n)
  79. /// </summary>
  80. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  81. public void Enqueue(TItem node, TPriority priority)
  82. {
  83. #if DEBUG
  84. if (node == null)
  85. {
  86. throw new ArgumentNullException(nameof(node));
  87. }
  88. if (_numNodes >= _nodes.Length - 1)
  89. {
  90. throw new InvalidOperationException("Queue is full - node cannot be added: " + node);
  91. }
  92. if (Contains(node))
  93. {
  94. throw new InvalidOperationException("Node is already enqueued: " + node);
  95. }
  96. #endif
  97. node.Priority = priority;
  98. _numNodes++;
  99. _nodes[_numNodes] = node;
  100. node.QueueIndex = _numNodes;
  101. node.InsertionIndex = _numNodesEverEnqueued++;
  102. CascadeUp(_nodes[_numNodes]);
  103. }
  104. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  105. private void Swap(TItem node1, TItem node2)
  106. {
  107. //Swap the nodes
  108. _nodes[node1.QueueIndex] = node2;
  109. _nodes[node2.QueueIndex] = node1;
  110. //Swap their indicies
  111. int temp = node1.QueueIndex;
  112. node1.QueueIndex = node2.QueueIndex;
  113. node2.QueueIndex = temp;
  114. }
  115. //Performance appears to be slightly better when this is NOT inlined o_O
  116. private void CascadeUp(TItem node)
  117. {
  118. //aka Heapify-up
  119. int parent = node.QueueIndex / 2;
  120. while (parent >= 1)
  121. {
  122. var parentNode = _nodes[parent];
  123. if (HasHigherPriority(parentNode, node))
  124. break;
  125. //Node has lower priority value, so move it up the heap
  126. Swap(node, parentNode); //For some reason, this is faster with Swap() rather than (less..?) individual operations, like in CascadeDown()
  127. parent = node.QueueIndex / 2;
  128. }
  129. }
  130. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  131. private void CascadeDown(TItem node)
  132. {
  133. //aka Heapify-down
  134. TItem newParent;
  135. int finalQueueIndex = node.QueueIndex;
  136. while (true)
  137. {
  138. newParent = node;
  139. int childLeftIndex = 2 * finalQueueIndex;
  140. //Check if the left-child is higher-priority than the current node
  141. if (childLeftIndex > _numNodes)
  142. {
  143. //This could be placed outside the loop, but then we'd have to check newParent != node twice
  144. node.QueueIndex = finalQueueIndex;
  145. _nodes[finalQueueIndex] = node;
  146. break;
  147. }
  148. var childLeft = _nodes[childLeftIndex];
  149. if (HasHigherPriority(childLeft, newParent))
  150. {
  151. newParent = childLeft;
  152. }
  153. //Check if the right-child is higher-priority than either the current node or the left child
  154. int childRightIndex = childLeftIndex + 1;
  155. if (childRightIndex <= _numNodes)
  156. {
  157. var childRight = _nodes[childRightIndex];
  158. if (HasHigherPriority(childRight, newParent))
  159. {
  160. newParent = childRight;
  161. }
  162. }
  163. //If either of the children has higher (smaller) priority, swap and continue cascading
  164. if (newParent != node)
  165. {
  166. //Move new parent to its new index. node will be moved once, at the end
  167. //Doing it this way is one less assignment operation than calling Swap()
  168. _nodes[finalQueueIndex] = newParent;
  169. int temp = newParent.QueueIndex;
  170. newParent.QueueIndex = finalQueueIndex;
  171. finalQueueIndex = temp;
  172. }
  173. else
  174. {
  175. //See note above
  176. node.QueueIndex = finalQueueIndex;
  177. _nodes[finalQueueIndex] = node;
  178. break;
  179. }
  180. }
  181. }
  182. /// <summary>
  183. /// Returns true if 'higher' has higher priority than 'lower', false otherwise.
  184. /// Note that calling HasHigherPriority(node, node) (ie. both arguments the same node) will return false
  185. /// </summary>
  186. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  187. private bool HasHigherPriority(TItem higher, TItem lower)
  188. {
  189. var cmp = higher.Priority.CompareTo(lower.Priority);
  190. return (cmp < 0 || (cmp == 0 && higher.InsertionIndex < lower.InsertionIndex));
  191. }
  192. /// <summary>
  193. /// Removes the head of the queue (node with minimum priority; ties are broken by order of insertion), and returns it.
  194. /// If queue is empty, result is undefined
  195. /// O(log n)
  196. /// </summary>
  197. public bool TryDequeue(out TItem item)
  198. {
  199. if (_numNodes <= 0)
  200. {
  201. item = default(TItem);
  202. return false;
  203. }
  204. #if DEBUG
  205. if (!IsValidQueue())
  206. {
  207. throw new InvalidOperationException("Queue has been corrupted (Did you update a node priority manually instead of calling UpdatePriority()?" +
  208. "Or add the same node to two different queues?)");
  209. }
  210. #endif
  211. var returnMe = _nodes[1];
  212. Remove(returnMe);
  213. item = returnMe;
  214. return true;
  215. }
  216. /// <summary>
  217. /// Resize the queue so it can accept more nodes. All currently enqueued nodes are remain.
  218. /// Attempting to decrease the queue size to a size too small to hold the existing nodes results in undefined behavior
  219. /// O(n)
  220. /// </summary>
  221. public void Resize(int maxNodes)
  222. {
  223. #if DEBUG
  224. if (maxNodes <= 0)
  225. {
  226. throw new InvalidOperationException("Queue size cannot be smaller than 1");
  227. }
  228. if (maxNodes < _numNodes)
  229. {
  230. throw new InvalidOperationException("Called Resize(" + maxNodes + "), but current queue contains " + _numNodes + " nodes");
  231. }
  232. #endif
  233. TItem[] newArray = new TItem[maxNodes + 1];
  234. int highestIndexToCopy = Math.Min(maxNodes, _numNodes);
  235. for (int i = 1; i <= highestIndexToCopy; i++)
  236. {
  237. newArray[i] = _nodes[i];
  238. }
  239. _nodes = newArray;
  240. }
  241. /// <summary>
  242. /// Returns the head of the queue, without removing it (use Dequeue() for that).
  243. /// If the queue is empty, behavior is undefined.
  244. /// O(1)
  245. /// </summary>
  246. public TItem First
  247. {
  248. get
  249. {
  250. #if DEBUG
  251. if (_numNodes <= 0)
  252. {
  253. throw new InvalidOperationException("Cannot call .First on an empty queue");
  254. }
  255. #endif
  256. return _nodes[1];
  257. }
  258. }
  259. /// <summary>
  260. /// This method must be called on a node every time its priority changes while it is in the queue.
  261. /// <b>Forgetting to call this method will result in a corrupted queue!</b>
  262. /// Calling this method on a node not in the queue results in undefined behavior
  263. /// O(log n)
  264. /// </summary>
  265. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  266. public void UpdatePriority(TItem node, TPriority priority)
  267. {
  268. #if DEBUG
  269. if (node == null)
  270. {
  271. throw new ArgumentNullException(nameof(node));
  272. }
  273. if (!Contains(node))
  274. {
  275. throw new InvalidOperationException("Cannot call UpdatePriority() on a node which is not enqueued: " + node);
  276. }
  277. #endif
  278. node.Priority = priority;
  279. OnNodeUpdated(node);
  280. }
  281. private void OnNodeUpdated(TItem node)
  282. {
  283. //Bubble the updated node up or down as appropriate
  284. int parentIndex = node.QueueIndex / 2;
  285. var parentNode = _nodes[parentIndex];
  286. if (parentIndex > 0 && HasHigherPriority(node, parentNode))
  287. {
  288. CascadeUp(node);
  289. }
  290. else
  291. {
  292. //Note that CascadeDown will be called if parentNode == node (that is, node is the root)
  293. CascadeDown(node);
  294. }
  295. }
  296. /// <summary>
  297. /// Removes a node from the queue. The node does not need to be the head of the queue.
  298. /// If the node is not in the queue, the result is undefined. If unsure, check Contains() first
  299. /// O(log n)
  300. /// </summary>
  301. public void Remove(TItem node)
  302. {
  303. #if DEBUG
  304. if (node == null)
  305. {
  306. throw new ArgumentNullException(nameof(node));
  307. }
  308. if (!Contains(node))
  309. {
  310. throw new InvalidOperationException("Cannot call Remove() on a node which is not enqueued: " + node);
  311. }
  312. #endif
  313. //If the node is already the last node, we can remove it immediately
  314. if (node.QueueIndex == _numNodes)
  315. {
  316. _nodes[_numNodes] = null;
  317. _numNodes--;
  318. return;
  319. }
  320. //Swap the node with the last node
  321. var formerLastNode = _nodes[_numNodes];
  322. Swap(node, formerLastNode);
  323. _nodes[_numNodes] = null;
  324. _numNodes--;
  325. //Now bubble formerLastNode (which is no longer the last node) up or down as appropriate
  326. OnNodeUpdated(formerLastNode);
  327. }
  328. public IEnumerator<TItem> GetEnumerator()
  329. {
  330. for (int i = 1; i <= _numNodes; i++)
  331. yield return _nodes[i];
  332. }
  333. IEnumerator IEnumerable.GetEnumerator()
  334. {
  335. return GetEnumerator();
  336. }
  337. /// <summary>
  338. /// <b>Should not be called in production code.</b>
  339. /// Checks to make sure the queue is still in a valid state. Used for testing/debugging the queue.
  340. /// </summary>
  341. public bool IsValidQueue()
  342. {
  343. for (int i = 1; i < _nodes.Length; i++)
  344. {
  345. if (_nodes[i] != null)
  346. {
  347. int childLeftIndex = 2 * i;
  348. if (childLeftIndex < _nodes.Length && _nodes[childLeftIndex] != null && HasHigherPriority(_nodes[childLeftIndex], _nodes[i]))
  349. return false;
  350. int childRightIndex = childLeftIndex + 1;
  351. if (childRightIndex < _nodes.Length && _nodes[childRightIndex] != null && HasHigherPriority(_nodes[childRightIndex], _nodes[i]))
  352. return false;
  353. }
  354. }
  355. return true;
  356. }
  357. }
  358. }