GenericPriorityQueue.cs 14 KB

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