如何从priority_queue中删除不在顶部的元素

How to remove element not at top from priority_queue?

本文关键字:顶部 元素 删除 priority queue      更新时间:2023-10-16

在我的程序中,我需要从优先级队列中删除不在顶部的元素。这能做到吗?如果没有,请建议一种方法,而不是创建自己的堆。

标准priority_queue<T>可以通过继承进行自定义。它具有受保护的成员ccomp,这些成员可以在后代类中引用。

template<typename T>
class custom_priority_queue : public std::priority_queue<T, std::vector<T>>
{
  public:
      bool remove(const T& value) {
          auto it = std::find(this->c.begin(), this->c.end(), value);
       
          if (it == this->c.end()) {
              return false;
          }
          if (it == this->c.begin()) {
              // deque the top element
              this->pop();
          }    
          else {
              // remove element and re-heap
              this->c.erase(it);
              std::make_heap(this->c.begin(), this->c.end(), this->comp);
         }
         return true;
     }
};
void main()
{
   custom_priority_queue<int> queue;
   queue.push(10);
   queue.push(2);
   queue.push(4);
   queue.push(6);
   queue.push(3);
   queue.remove(6);
   while (!queue.empty())
   {
      std::cout << queue.top();
      queue.pop();
      if (!queue.empty())
      {
        std::cout << ", ";
      }
   }
 }

输出:

10, 4, 3, 2

最好的解决方案是使用 std::set。集合提供了允许它用作最小/最大堆(或优先级队列)的方法。

std::set<int> pq;
//accessing the smallest element(use as min heap)
*pq.begin();
//accessing the largest element (use as max heap)
*pq.rbegin();

此外,集合还允许随机删除。

//to delete the integer '6'
auto it = pq.find(6);
pq.erase(it);
处理

priority_queue STL 删除的一个巧妙的小技巧 - 使用另一个priority_queue,比如del_pq。继续插入所有删除值。当您从原始优先级队列中弹出值时,请检查del_pq顶部,看看我们是否要删除它。如果匹配,请从原始priority_queue中删除该值。

此方法实现了一种延迟删除原始优先级队列中的值的方法。可以占用两倍的内存,但平均删除和插入仍然O(logN)

Pradip 和 MASh 牺牲了时间来实现删除操作。但是,如果时间复杂度对您很重要,我建议您使用哈希min_heap。哈希表存储值指针,指针指向min_heap。这意味着您可以花费 O(1) 时间来查找 min_heap 中的值,并花费 O(log(n)) 来删除(筛选或筛选)元素。

请注意 ,以下方法可以解决问题,但不是优化的解决方案。有关优化方法,请查看其他答案。

让你要删除priority_queue<type> Q中的第 5 个元素。然后你可以这样做,就像:

vector<type> tempQ;
int i = 0;
int n = 5;
type t;
// backup n-1 items
while(i < n-1)
{
    tempQ.push_back(Q.top());
    Q.pop();        
    i++;
}
// remove the nth item
Q.pop();
// restore the backed up items
i = 0;
while(i < n-1)
{
    t = tempQ[i++];
    Q.push(t);
}