【问题标题】:Python - hash heap implementationPython - 哈希堆实现
【发布时间】: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


    【解决方案1】:

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

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

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

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

    4. 删除具有给定键的项目:仅从哈希表中删除具有给定键的条目。

    5. 访问最小key:如果在hashtable中没有找到堆顶的元素,则丢弃它;重复,直到顶部的键出现在哈希表中。

    【讨论】:

    • 感谢您的意见!访问最小密钥的目的是什么?
    • @enaJ 你应该知道得更多。这是最小堆数据结构的主要功能。如果您不需要访问最小的键,为什么您的问题是围绕最小堆构建的?
    • 我对中的第一项表示一个节点,第二项表示与该节点连接的边。这个问题的大局是在 1 分钟的滚动时间窗口内更新一个带有顶点和节点的图。
    • @enaJ min-heap 对此有何帮助?
    • 我希望能够更改堆中的任何特定项目。不一定是最小的
    猜你喜欢
    • 2014-10-18
    • 2016-03-25
    • 2015-02-02
    • 2021-07-22
    • 2012-06-03
    • 2011-10-14
    • 2011-09-15
    • 2010-11-07
    相关资源
    最近更新 更多