【问题标题】:Priority Queue remove items with same priority first one entered优先级队列删除具有相同优先级的项目第一个进入
【发布时间】:2019-02-26 20:48:27
【问题描述】:

我创建了一个优先级队列,它可以按顺序输入项目并按顺序删除它们。即使两个数字具有相同的优先级,它也会删除第一个输入的数字。

如果存在三个具有相同优先级的数字,则不会删除第一个。我将如何去做,还是应该这样做?

出队函数:

public void deQueue(Animal item)
{
    item = items.elements[0];
    items.elements[0] = items.elements[numItems - 1];
    numItems--;
    items.ReheapDown(0, numItems - 1);
}

ReheapDown 函数:

public void ReheapDown(int root, int bottom)
{
    int maxchild, rightchild, leftchild;
    leftchild = root * 2 + 1;
    rightchild = root * 2 + 2;

    if (leftchild <= bottom)
    {
        if (leftchild == bottom)
            maxchild = leftchild;
        else
        {
            if (elements[leftchild].priority <= elements[rightchild].priority)
                maxchild = rightchild;
            else
                maxchild = leftchild;
        }

        if (elements[root].priority < elements[maxchild].priority)
        {
            Swap(elements, root, maxchild);
            ReheapDown(maxchild, bottom);
        }
    }
}

【问题讨论】:

    标签: c# queue priority-queue


    【解决方案1】:

    在这一行

    if (elements[leftchild].priority <= elements[rightchild].priority)
    

    如果它们相等,则交换元素。因此,假设您按顺序输入数字[2, 2, 1, 3]。让我们将第二个 2 称为“2*”,以区别于第一个。结果堆是:

          1
        /   \
       2     2*
      /
     3
    

    现在,您删除 1。那么你用3替换1

          3
        /   \
       2     2*
    

    在您的ReheapDown 方法中,父母有两个孩子,您选择的是最小的孩子。当您比较两个2 时,您会得到以下代码:

    if (elements[leftchild].priority <= elements[rightchild].priority)
        maxchild = rightchild;
    else
        maxchild = leftchild;
    

    由于2 == 2,它设置maxchild = rightchild,所以新的根变成2*——第二个输入的2。你的堆现在看起来像这样:

          2*
        /   \
       2     3
    

    接下来要删除的将是2*

    那么,您可能会想,如果您将 &lt;= 更改为 &lt;,它将解决您的问题。但它不会。

    当您考虑堆可能发生变异的所有不同方式时,除非您提供其他信息,否则无法保证相同的项目会按照插入的顺序被删除。考虑一下如果您按[1, 3, 2, 2*] 的顺序输入项目会发生什么。结果堆是:

          1
        /   \
       2*    2
      /
     3
    

    如果您删除 1,您最终会得到:

          3
        /   \
       2*    2
    

    在这种情况下,&lt;= 会帮助您。但在前一种情况下,它不会。

    唯一保证相等项目的移除顺序的方法是在比较中添加第二个条件 - 基本上,您必须使这些相等的项目不相等。您需要在密钥中添加日期戳或序列号,以便识别广告订单。

    【讨论】:

      猜你喜欢
      • 2011-01-18
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 2012-03-06
      • 2011-12-20
      相关资源
      最近更新 更多