GenericPriorityQueue.cs 14 KB

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