52 lines
1.3 KiB
C#
52 lines
1.3 KiB
C#
using System.Collections.Generic;
|
|
|
|
public class PriorityQueue<T>
|
|
{
|
|
// The items and priorities.
|
|
List<T> Values = new List<T>();
|
|
List<int> Priorities = new List<int>();
|
|
|
|
// Return the number of items in the queue.
|
|
public int NumItems
|
|
{
|
|
get
|
|
{
|
|
return Values.Count;
|
|
}
|
|
}
|
|
|
|
// Add an item to the queue.
|
|
|
|
public void AddAt(int index,T new_value, int new_priority)
|
|
{
|
|
Values.Insert(index, new_value);
|
|
Priorities.Insert(index, new_priority);
|
|
}
|
|
|
|
public void Enqueue(T new_value, int new_priority)
|
|
{
|
|
var index = 0;
|
|
foreach (var item in Priorities)
|
|
{
|
|
if (item < new_priority) index++;
|
|
else break;
|
|
}
|
|
Values.Insert(index,new_value);
|
|
Priorities.Insert(index,new_priority);
|
|
}
|
|
|
|
// Remove the item with the largest priority from the queue.
|
|
public KeyValuePair<T,int> Dequeue()
|
|
{
|
|
// Find the hightest priority.
|
|
var best_index = 0;
|
|
|
|
// Return the corresponding item.
|
|
var top_value = Values[best_index];
|
|
var top_priotiy = Priorities[best_index];
|
|
// Remove the item from the lists.
|
|
Values.RemoveAt(best_index);
|
|
Priorities.RemoveAt(best_index);
|
|
return new KeyValuePair<T,int>(top_value,top_priotiy);
|
|
}
|
|
} |