Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. class PriorityQueue<TKey, TValue>
  2. {
  3. private List<KeyValuePair<TKey, TValue>> _heap;
  4. public int size;
  5. private IComparer<TKey> _comparer;
  6.  
  7. public PriorityQueue() : this(Comparer<TKey>.Default)
  8. {
  9. }
  10.  
  11. public PriorityQueue(IComparer<TKey> comparer)
  12. {
  13. _heap = new List<KeyValuePair<TKey, TValue>>();
  14. _comparer = comparer;
  15. }
  16.  
  17. public void Enqueue(TKey key, TValue value)
  18. {
  19. Console.WriteLine(_heap.Capacity);
  20. KeyValuePair<TKey, TValue> tmp = new KeyValuePair<TKey, TValue>(key, value);
  21. _heap.Add(tmp);
  22. ++size;
  23. SiftUp();
  24. }
  25.  
  26. private void SiftUp()
  27. {
  28. int cur = _heap.Count - 1;
  29. int parents = (cur - 1)/2;
  30. while (cur > 0)
  31. {
  32. if (!Swap(cur, parents))
  33. break;
  34.  
  35. cur = parents;
  36. parents = (cur - 1)/2;
  37. }
  38. }
  39.  
  40. private void SiftDown()
  41. {
  42. if (size < 2) return;
  43. int cur = 0;
  44. int child = 0;
  45.  
  46. while (cur < size)
  47. {
  48. child = cur*2 + 1;
  49. if (child > size - 1) return;
  50. if (child + 1 < size && _comparer.Compare(_heap[child].Key, _heap[child + 1].Key) > 0)
  51. ++child;
  52.  
  53. if (!Swap(child, cur))
  54. break;
  55.  
  56. cur = child;
  57. }
  58. }
  59.  
  60. public KeyValuePair<TKey, TValue> Dequeue()
  61. {
  62. KeyValuePair<TKey, TValue> result = _heap[0];
  63. int idx = _heap.Count - 1;
  64. _heap[0] = _heap[idx];
  65. _heap.RemoveAt(idx);
  66. --size;
  67. SiftDown();
  68. return result;
  69. }
  70.  
  71. private bool Swap(int parents, int cur)
  72. {
  73. if (_comparer.Compare(_heap[parents].Key, _heap[cur].Key) < 0)
  74. {
  75. KeyValuePair<TKey, TValue> tmp = _heap[parents];
  76. _heap[parents] = _heap[cur];
  77. _heap[cur] = tmp;
  78. return true;
  79. }
  80. return false;
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement