合并使用优先级队列K

编程入门 行业动态 更新时间:2024-10-23 23:31:36
本文介绍了合并使用优先级队列K-有序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在问我的算法类做一个K-方式合并算法是的O(nlogk)搜索后,我发现它可以通过制作A K长度优先级队列和每个列表的第一个元素入队不能做到。提取最低,其追加到结果和从入队的元素已经被提取的列表。我感到困惑:

I have been asked in my algorithm class to make a K-way merge algorithm which is of O(nlogk) After searching i found it could be done via making a k length priority queue and enqueuing it with the first element of each list. Extract the minimum, append it to result and enqueue from the list whose element has been extracted. I am confused about:

  • 它如何知道当一个特定的列表已用尽,假设列表比其他列表中所有其他元素更小的元素?

  • How will it know when a particular list is exhausted, suppose a list has smaller elements than every other element in other lists?

    它如何知道是哪个列表中(如果structue不是用来定义)的元素?

    How will it know the element was of which list (if a structue is not used to define)?

    是怎样的时间复杂度 O(nlogk)?

    编辑:

    这将是一个多一点有益的,如果有人能写下来的算法分步进行,因为所有我读它在句子,它很难理解事情是这样的,如果有人可以在算法写下来可能会有所帮助理解了。

    It would be a bit more helpful if someone can write down the algorithm step-wise, because all i have read it is in sentences and its hard to understand the way it is, if someone could write down the algorithm might be helpful to understand.

    推荐答案

    下面是一些Python code,做了合并。

    Here's some Python code that does the merging.

    import heapq def addtoheap(h, i, it): try: heapq.heappush(h, (next(it), i)) except StopIteration: pass def mergek(*lists): its = map(iter, lists) h = [] for i, it in enumerate(its): addtoheap(h, i, it) while h: v, i = heapq.heappop(h) addtoheap(h, i, its[i]) yield v for x in mergek([1, 3, 5], [2, 4, 6], [7, 8, 9], [10]): print x

    为什么是O(N日志K)?那么对于删除的每个值,有一堆流行和可能的堆推(这两者都是为O(log k))的。既然我们删除n个元素,它是O(N日志K)。

    Why is it O(n log k)? Well for each value removed, there's a heap pop and possibly a heap push (both of which are O(log k)). Since we remove n elements, it's O(n log k).

  • 更多推荐

    合并使用优先级队列K

    本文发布于:2023-11-30 11:49:47,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1649860.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:优先级   队列

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!