GenericPriorityQueue.cs 14 KB

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