-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPriorityQueue.cs
More file actions
82 lines (78 loc) · 2.49 KB
/
PriorityQueue.cs
File metadata and controls
82 lines (78 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Collections.Generic;
using System.Linq;
namespace SharpAlgos
{
public class PriorityQueue<T>
{
private readonly bool _isMinPriorityQueue;
private int _count;
private readonly SortedDictionary<double, HashSet<T>> _q = new SortedDictionary<double, HashSet<T>>();
public PriorityQueue(bool isMinPriorityQueue)
{
_isMinPriorityQueue = isMinPriorityQueue;
}
public int Count => _count;
/// <summary>
/// Add new element (with priority = 'priority') in the queue
/// Complexity: o( log(n) )
/// </summary>
/// <param name="t">the element to add</param>
/// <param name="priority">the associate priority</param>
public void Enqueue(T t, double priority)
{
if (!_isMinPriorityQueue)
{
priority = InvertPriority(priority);
}
if (!_q.ContainsKey(priority))
{
_q.Add(priority, new HashSet<T>());
}
_q[priority].Add(t);
++_count;
}
/// <summary>
/// Update the priority of an existing element 't' from 'oldPriority' to 'newPriority'
/// Complexity: o( log(n) )
/// </summary>
/// <param name="t">an existing element in the queue</param>
/// <param name="oldPriority">the old element priority</param>
/// <param name="newPriority">the new element priority</param>
public void UpdatePriority(T t, double oldPriority, double newPriority)
{
if (!_isMinPriorityQueue)
{
oldPriority = InvertPriority (oldPriority);
}
_q[oldPriority].Remove(t);
--_count;
Enqueue(t, newPriority);
}
private static double InvertPriority(double priority)
{
if (priority == double.MaxValue)
{
return double.MinValue;
}
if (priority == double.MinValue)
{
return double.MaxValue;
}
return -priority;
}
public T Dequeue()
{
foreach (var e in _q.Values)
{
if (e.Count != 0)
{
var result = e.First();
e.Remove(result);
--_count;
return result;
}
}
return default(T);
}
}
}