Python - 哈希堆实现

时间:2016-07-10 19:51:18

标签: data-structures heap hashtable

我有一个流数据,我通过将它们逐个推入堆(优先级队列)来维护它们,生成的堆看起来像:

[(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版本代码?

1 个答案:

答案 0 :(得分:2)

我的理解是,对中的第一项用作键,第二项用作数据有效负载。然后我会提出另一种方法,有点类似于this answer,但更简单。

  1. 让哈希表成为数据存储的主要数据结构,最小堆是用于维护数据集中当前最小键的辅助数据结构。

  2. 插入新项目:将数据添加到哈希表和最小堆中。

  3. 更新给定密钥的值:仅更新哈希表中的值。

  4. 使用给定密钥删除项目:仅使用哈希表中的给定密钥删除条目。

  5. 访问最小的密钥:如果在哈希表中找不到堆顶部的元素,则删除它;重复,直到哈希表中存在顶部键。