实施提取物分钟​​的O(1)提取物

2023-09-11 23:09:50 作者:7ゎ.无爱一身轻ゝ

可能重复:   Implement这push_rear队列中的(),pop_front()和get_min()都是常量时间的操作。

我需要实现一个FIFO数据结构,其中摊销入队,出队的成本和提取敏是O(1)。

I need to implement a FIFO data structure in which amortized cost of Enqueue, Dequeue and Extract-Min is O(1).

我曾想过使用常规的队列,这将有O(1)入队和出队使用链表,然后进行提取民我会去通过阵列以获得最小和removie它。的成本,这将是为O(n),但并不会带来摊销成本为O(1)。

I have thought about using a regular queue which will have O(1) enqueue and dequeue using linked lists and then for Extract-Min I would go through the array to get the min and removie it. the cost for that would be O(n) though and that would not bring the amortized cost to O(1).

任何帮助或暗示将AP preciated。

Any help or hints would be appreciated.

推荐答案

可以实现与总是指向与队列的最值的节点一个额外的成员队列。入队()必须轻微的修改,通过下伪code:

You can implement a queue with an extra member which always points to the node with the least value of the queue. The Enqueue() has to be slight modified as shown by the pseudo code below:

void enqueue( data_t val )
{
  back->m_data = val; // back is a pointer to the end of the queue.

  // m_Min should be initialized with a large value.
  if (back->m_data <= m_Min->m_data)
  {
    m_Min = back;
  }
  else // => back->m_data > m_Min->m_data
  {
    swap(back->m_data, m_Min->m_data);
    m_Min = back;
  }
}

以上修改将确保入队,出队和extract_min为O的所有运行(1)。

The above modification will ensure that enqueue, dequeue and extract_min all run in O(1).

data_t dequeue( )
{
  data_t front_data = front->m_data;

  prev_front = front;
  front = front->next;

  dump prev_front;
  return front_data;
}

所以,当达到 M_MIN 队列中有这将是最值只有一个元素。

So when front reaches m_Min the queue has only one element which will be the least value.

data_t min()
{
  return m_Min->m_data;
}

编辑: if区块中的排队()从我的previous版本修改。入队()基本上是在推动年底的新值。但互换其中previous节点,如果它是大于当前分钟(这是在队列中的最后节点持有)。

The if-block in enqueue() is modified from my previous version. The enqueue() basically pushes the new value at the end. But swaps with previous node if it is greater than the current min (which is held in the last node of the queue).

有关例如,如果输入序列是​​5,3,7,1,4,6,8

For e.g if the input sequence is 5, 3, 7, 1, 4, 6, 8.

1.
front -> 5 <- back
         ^min

2.
front -> 5 3 <- back.
         ^min

front -> 5 3 <- back.
           ^min

3.
front -> 5 3 7 <- back
           ^min

front -> 5 7 3 <- back
             ^min

4.
front -> 5 7 3 1 <- back
             ^min

front -> 5 7 3 1 <- back
               ^min

5.
front -> 5 7 3 1 4 <- back
               ^min

front -> 5 7 3 4 1 <- back
                 ^min

6.
front -> 5 7 3 4 1 6 <- back
                 ^min

front -> 5 7 3 4 6 1 <- back
                   ^min

7.
front -> 5 7 3 4 6 1 8 <- back
                   ^min

front -> 5 7 3 4 6 8 1 <- back
                     ^min

说你出列3项,队列会是这样的:

Say you dequeue 3 items, the queue will look like:

front -> 4 6 8 1 <- back
               ^min

因此​​,通过时间达到,队列将拥有这将是只有一个元素

So by the time front reached min, the queue will have only one element which will be min.

 
精彩推荐
图片推荐