簡體   English   中英

C# 優先隊列

[英]C# Priority Queue

我正在尋找具有如下界面的優先級隊列:

class PriorityQueue<T>
{
    public void Enqueue(T item, int priority)
    {
    }

    public T Dequeue()
    {
    }
}

我見過的所有實現都假設itemIComparable但我不喜歡這種方法; 我想在將其推入隊列時指定優先級。

如果不存在現成的實現,那么我自己做這件事的最佳方法是什么? 我應該使用什么底層數據結構? 某種自平衡樹,還是什么? 一個標准的 C#.net 結構會很好。

如果您有一個基於 IComparable 的現有優先級隊列實現,您可以輕松地使用它來構建您需要的結構:

public class CustomPriorityQueue<T>  // where T need NOT be IComparable
{
  private class PriorityQueueItem : IComparable<PriorityQueueItem>
  {
    private readonly T _item;
    private readonly int _priority:

    // obvious constructor, CompareTo implementation and Item accessor
  }

  // the existing PQ implementation where the item *does* need to be IComparable
  private readonly PriorityQueue<PriorityQueueItem> _inner = new PriorityQueue<PriorityQueueItem>();

  public void Enqueue(T item, int priority)
  {
    _inner.Enqueue(new PriorityQueueItem(item, priority));
  }

  public T Dequeue()
  {
    return _inner.Dequeue().Item;
  }
}

您可以添加安全檢查等等,但這是一個使用SortedList的非常簡單的實現:

class PriorityQueue<T> {
    SortedList<Pair<int>, T> _list;
    int count;

    public PriorityQueue() {
        _list = new SortedList<Pair<int>, T>(new PairComparer<int>());
    }

    public void Enqueue(T item, int priority) {
        _list.Add(new Pair<int>(priority, count), item);
        count++;
    }

    public T Dequeue() {
        T item = _list[_list.Keys[0]];
        _list.RemoveAt(0);
        return item;
    }
}

我假設較小的priority值對應於較高優先級的項目(這很容易修改)。

如果多個線程將訪問隊列,您也需要添加鎖定機制。 這很容易,但如果您需要這里的指導,請告訴我。

SortedList在內部實現為二叉樹。

上述實現需要以下幫助類。 這解決了 Lasse V. Karlsen 的評論,即不能使用使用SortedList的幼稚實現添加具有相同優先級的項目。

class Pair<T> {
    public T First { get; private set; }
    public T Second { get; private set; }

    public Pair(T first, T second) {
        First = first;
        Second = second;
    }

    public override int GetHashCode() {
        return First.GetHashCode() ^ Second.GetHashCode();
    }

    public override bool Equals(object other) {
        Pair<T> pair = other as Pair<T>;
        if (pair == null) {
            return false;
        }
        return (this.First.Equals(pair.First) && this.Second.Equals(pair.Second));
    }
}

class PairComparer<T> : IComparer<Pair<T>> where T : IComparable {
    public int Compare(Pair<T> x, Pair<T> y) {
        if (x.First.CompareTo(y.First) < 0) {
            return -1;
        }
        else if (x.First.CompareTo(y.First) > 0) {
            return 1;
        }
        else {
            return x.Second.CompareTo(y.Second);
        }
    }
}

您可以圍繞現有實現之一編寫一個包裝器,將接口修改為您的偏好:

using System;

class PriorityQueueThatYouDontLike<T> where T: IComparable<T>
{
    public void Enqueue(T item) { throw new NotImplementedException(); }
    public T Dequeue() { throw new NotImplementedException(); }
}

class PriorityQueue<T>
{
    class ItemWithPriority : IComparable<ItemWithPriority>
    {
        public ItemWithPriority(T t, int priority)
        {
            Item = t;
            Priority = priority;
        }

        public T Item {get; private set;}
        public int Priority {get; private set;}

        public int CompareTo(ItemWithPriority other)
        {
            return Priority.CompareTo(other.Priority);
        }
    }

    PriorityQueueThatYouDontLike<ItemWithPriority> q = new PriorityQueueThatYouDontLike<ItemWithPriority>();

    public void Enqueue(T item, int priority)
    {
        q.Enqueue(new ItemWithPriority(item, priority));
    }

    public T Dequeue()
    {
        return q.Dequeue().Item;
    }
}

這與 itowlson 的建議相同。 我只是花了更長的時間來寫我的,因為我填寫了更多的方法。 :-s

這是一個非常簡單的輕量級實現,對於推送和彈出都具有 O(log(n)) 性能。 它使用建立在 List<T> 之上的堆數據結構

/// <summary>Implements a priority queue of T, where T has an ordering.</summary>
/// Elements may be added to the queue in any order, but when we pull
/// elements out of the queue, they will be returned in 'ascending' order.
/// Adding new elements into the queue may be done at any time, so this is
/// useful to implement a dynamically growing and shrinking queue. Both adding
/// an element and removing the first element are log(N) operations. 
/// 
/// The queue is implemented using a priority-heap data structure. For more 
/// details on this elegant and simple data structure see "Programming Pearls"
/// in our library. The tree is implemented atop a list, where 2N and 2N+1 are
/// the child nodes of node N. The tree is balanced and left-aligned so there
/// are no 'holes' in this list. 
/// <typeparam name="T">Type T, should implement IComparable[T];</typeparam>
public class PriorityQueue<T> where T : IComparable<T> {
   /// <summary>Clear all the elements from the priority queue</summary>
   public void Clear () {
      mA.Clear ();
   }

   /// <summary>Add an element to the priority queue - O(log(n)) time operation.</summary>
   /// <param name="item">The item to be added to the queue</param>
   public void Add (T item) {
      // We add the item to the end of the list (at the bottom of the
      // tree). Then, the heap-property could be violated between this element
      // and it's parent. If this is the case, we swap this element with the 
      // parent (a safe operation to do since the element is known to be less
      // than it's parent). Now the element move one level up the tree. We repeat
      // this test with the element and it's new parent. The element, if lesser
      // than everybody else in the tree will eventually bubble all the way up
      // to the root of the tree (or the head of the list). It is easy to see 
      // this will take log(N) time, since we are working with a balanced binary
      // tree.
      int n = mA.Count; mA.Add (item);
      while (n != 0) {
         int p = n / 2;    // This is the 'parent' of this item
         if (mA[n].CompareTo (mA[p]) >= 0) break;  // Item >= parent
         T tmp = mA[n]; mA[n] = mA[p]; mA[p] = tmp; // Swap item and parent
         n = p;            // And continue
      }
   }

   /// <summary>Returns the number of elements in the queue.</summary>
   public int Count {
      get { return mA.Count; }
   }

   /// <summary>Returns true if the queue is empty.</summary>
   /// Trying to call Peek() or Next() on an empty queue will throw an exception.
   /// Check using Empty first before calling these methods.
   public bool Empty {
      get { return mA.Count == 0; }
   }

   /// <summary>Allows you to look at the first element waiting in the queue, without removing it.</summary>
   /// This element will be the one that will be returned if you subsequently call Next().
   public T Peek () {
      return mA[0];
   }

   /// <summary>Removes and returns the first element from the queue (least element)</summary>
   /// <returns>The first element in the queue, in ascending order.</returns>
   public T Next () {
      // The element to return is of course the first element in the array, 
      // or the root of the tree. However, this will leave a 'hole' there. We
      // fill up this hole with the last element from the array. This will 
      // break the heap property. So we bubble the element downwards by swapping
      // it with it's lower child until it reaches it's correct level. The lower
      // child (one of the orignal elements with index 1 or 2) will now be at the
      // head of the queue (root of the tree).
      T val = mA[0];
      int nMax = mA.Count - 1;
      mA[0] = mA[nMax]; mA.RemoveAt (nMax);  // Move the last element to the top

      int p = 0;
      while (true) {
         // c is the child we want to swap with. If there
         // is no child at all, then the heap is balanced
         int c = p * 2; if (c >= nMax) break;

         // If the second child is smaller than the first, that's the one
         // we want to swap with this parent.
         if (c + 1 < nMax && mA[c + 1].CompareTo (mA[c]) < 0) c++;
         // If the parent is already smaller than this smaller child, then
         // we are done
         if (mA[p].CompareTo (mA[c]) <= 0) break;

         // Othewise, swap parent and child, and follow down the parent
         T tmp = mA[p]; mA[p] = mA[c]; mA[c] = tmp;
         p = c;
      }
      return val;
   }

   /// <summary>The List we use for implementation.</summary>
   List<T> mA = new List<T> ();
}

這正是我高度優化的 C# priority-queue使用的接口。

它是專門為尋路應用程序(A* 等)開發的,但也可以完美地適用於任何其他應用程序。

public class User
{
    public string Name { get; private set; }
    public User(string name)
    {
        Name = name;
    }
}

...

var priorityQueue = new SimplePriorityQueue<User>();
priorityQueue.Enqueue(new User("Jason"), 1);
priorityQueue.Enqueue(new User("Joseph"), 10);

//Because it's a min-priority queue, the following line will return "Jason"
User user = priorityQueue.Dequeue();

這樣的事情有什么可怕的?

class PriorityQueue<TItem, TPriority> where TPriority : IComparable
{
    private SortedList<TPriority, Queue<TItem>> pq = new SortedList<TPriority, Queue<TItem>>();
    public int Count { get; private set; }

    public void Enqueue(TItem item, TPriority priority)
    {
        ++Count;
        if (!pq.ContainsKey(priority)) pq[priority] = new Queue<TItem>();
        pq[priority].Enqueue(item);
    }

    public TItem Dequeue()
    {
        --Count;
        var queue = pq.ElementAt(0).Value;
        if (queue.Count == 1) pq.RemoveAt(0);
        return queue.Dequeue();
    }
}

class PriorityQueue<TItem> : PriorityQueue<TItem, int> { }

我意識到您的問題專門要求基於非 IComparable 的實現,但我想指出Visual Studio Magazine最近的一篇文章。

http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx

@itowlson 的這篇文章可以給出完整的答案。

有點晚了,但我會在這里添加以供參考

https://github.com/ERufian/Algs4-CSharp

鍵值對優先級隊列在 Algs4/IndexMaxPQ.cs、Algs4/IndexMinPQ.cs 和 Algs4/IndexPQDictionary.cs 中實現

筆記:

  1. 如果優先級不是 IComparable 的,則可以在構造函數中指定 IComparer
  2. 不是將對象及其優先級入隊,而是入隊的是索引及其優先級(對於原始問題,需要單獨的 List 或 T[] 將該索引轉換為預期結果)

.NET6 終於為 PriorityQueue 提供了一個 API

這里

似乎您可以使用一系列隊列來創建自己的隊列,每個優先級一個。 字典,只需將其添加到適當的字典中即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM