【发布时间】:2016-11-12 17:58:48
【问题描述】:
我有一个流数据来了,我通过将它们一一推入堆(优先队列)来维护它们,生成的堆看起来像:
[(a,1), (b,2), (c, 7), (d, 2), ...]
因为我需要不断更新项目(例如,将 (a,1) 更改为 (a, 2),或删除 (c,7)))。为了有效地查找和删除堆中的项目,我想构建一个哈希表,将堆中每个项目的位置存储在哈希表中。
这样每次我想更新一个项目时,我都可以使用哈希表找到它并在堆中轻松进行更改,同时更新每个项目在哈希表中的位置。
在这篇文章中也提出了同样的问题:How to implement O(1) deletion on min-heap with hashtable,c++ 代码如下:
template<typename state, typename CmpKey, class dataStructure>
bool AStarOpenClosed<state, CmpKey, dataStructure>::HeapifyUp(unsigned int index)
{
if (index == 0) return false;
int parent = (index-1)/2;
CmpKey compare;
if (compare(elements[theHeap[parent]], elements[theHeap[index]]))
{
// Perform normal heap operations
unsigned int tmp = theHeap[parent];
theHeap[parent] = theHeap[index];
theHeap[index] = tmp;
// Update the element location in the hash table
elements[theHeap[parent]].openLocation = parent;
elements[theHeap[index]].openLocation = index;
HeapifyUp(parent);
return true;
}
return false;
}
我对c++没有什么经验,想知道是否有人可以帮助我解释这个想法或提供这种实现的python版本代码?
【问题讨论】:
标签: data-structures heap hashtable