Fibonacci堆减键实战:父节点已经丢过一个孩子,为什么第二次要连它也剪下来

10-07 6阅读

把一个堆内节点的优先级降低到父亲以下,直接剪下来放到根列表即可恢复堆序。但如果父亲可以无限丢孩子,树的度数就不再反映它还剩多少节点,之后删除最小值时便可能付出失控成本。

Fibonacci堆用一个mark位记住非根节点已经丢过一个孩子。第二次丢失时,连父亲一起剪下,并可能一路向上触发级联。本文实现插入、带句柄减键与弹出最小值,重点核对这份“只容忍一次”的历史记录。

Fibonacci堆减键实战:父节点已经丢过一个孩子,为什么第二次要连它也剪下来

AI模型生成的概念示意:带发光记号的吊坠接头与落入托盘的枝组表达记账和级联切断;不是精确堆结构、节点数或真实运行图。

完整程序与实际输出

将以下完整源码保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码0、标准错误为空;只使用标准库与本地教学数据。

from random import Random


class Node:
    def __init__(self, owner, serial, key):
        self.owner, self.serial, self.key = owner, serial, key
        self.parent, self.mark, self.alive = None, False, True
        self.children = {}

    def priority(self):
        return self.key, self.serial


class FibonacciHeap:
    def __init__(self):
        self.roots, self.minimum = {}, None
        self.size, self.next_serial = 0, 0
        self.cuts = self.cascades = 0

    def check_key(self, key):
        if type(key) is not int or abs(key) > 10**9:
            raise ValueError("bounded integer priority required")

    def insert(self, key):
        self.check_key(key)
        if self.size >= 1024:
            raise ValueError("active node budget exceeded")
        node = Node(self, self.next_serial, key)
        self.next_serial += 1
        self.roots[node.serial] = node
        if self.minimum is None or node.priority() < self.minimum.priority():
            self.minimum = node
        self.size += 1
        return node

    def cut(self, node, parent):
        del parent.children[node.serial]
        node.parent, node.mark = None, False
        self.roots[node.serial] = node
        self.cuts += 1

    def decrease(self, node, key):
        self.check_key(key)
        if type(node) is not Node or node.owner is not self or not node.alive:
            raise ValueError("live handle from this heap required")
        if key > node.key:
            raise ValueError("new priority must not increase")
        node.key = key
        parent = node.parent
        if parent is not None and node.priority() < parent.priority():
            self.cut(node, parent)
            while parent.parent is not None:
                if not parent.mark:
                    parent.mark = True
                    break
                grand = parent.parent
                self.cut(parent, grand)
                self.cascades += 1
                parent = grand
        if node.priority() < self.minimum.priority():
            self.minimum = node

    def pop(self):
        root = self.minimum
        if root is None:
            raise IndexError("empty heap")
        del self.roots[root.serial]
        for child in root.children.values():
            child.parent, child.mark = None, False
            self.roots[child.serial] = child
        root.children = {}
        root.alive = False
        self.size -= 1
        buckets = {}
        for node in list(self.roots.values()):
            degree = len(node.children)
            while degree in buckets:
                other = buckets.pop(degree)
                if other.priority() < node.priority():
                    node, other = other, node
                other.parent, other.mark = node, False
                node.children[other.serial] = other
                degree += 1
            buckets[degree] = node
        self.roots = {node.serial: node for node in buckets.values()}
        self.minimum = min(self.roots.values(), key=lambda node: node.priority(), default=None)
        return root.priority()

    def inspect(self):
        seen, values, marked = set(), [], 0
        def visit(node, parent):
            nonlocal marked
            assert node.serial not in seen and node.parent is parent
            assert node.owner is self and node.alive
            seen.add(node.serial)
            values.append(node.priority())
            assert parent is not None or not node.mark
            marked += int(node.mark)
            count = 1
            for serial, child in node.children.items():
                assert serial == child.serial and node.priority() <= child.priority()
                count += visit(child, node)
            a, b = 0, 1
            for unused in range(len(node.children)+2):
                a, b = b, a+b
            assert count >= a
            return count
        for serial, root in self.roots.items():
            assert serial == root.serial
            visit(root, None)
        assert len(seen) == self.size
        expected = min(values, default=None)
        assert (self.minimum.priority() if self.minimum is not None else None) == expected
        return sorted(values), len(self.roots), marked


heap = FibonacciHeap()
handles = [heap.insert(i) for i in range(65)]
assert heap.pop() == (0, 0)
heap.inspect()
child = next(node for node in handles if node.alive and node.parent is not None
             and node.parent.parent is not None and len(node.children) >= 2
             and len(node.parent.children) >= 2)
parent = child.parent
sibling = next(node for node in parent.children.values() if node is not child)
first, second = list(child.children.values())[:2]
heap.decrease(sibling, -100)
assert parent.mark
heap.inspect()
heap.decrease(first, -101)
assert child.mark and parent.mark
print("two nonroot ancestors marked:", child.mark, parent.mark)
before = heap.cascades
heap.decrease(second, -102)
assert child.parent is None and parent.parent is None
assert not child.mark and not parent.mark
print("cascading ancestor cuts in final decrease:", heap.cascades-before)
print("root count / marked count:", heap.inspect()[1:])
print("three new minima:", [heap.pop() for unused in range(3)])
heap.inspect()

rng, heap, live = Random(6812), FibonacciHeap(), {}
for unused in range(4000):
    action = rng.randrange(3)
    if not live or (action == 0 and len(live) < 120):
        node = heap.insert(rng.randrange(-1000, 1001))
        live[node.serial] = [node, node.key]
    elif action == 1:
        serial = rng.choice(list(live))
        node, old = live[serial]
        new = old - rng.randrange(30)
        heap.decrease(node, new)
        live[serial][1] = new
    else:
        wanted = min((key, serial) for serial, (node, key) in live.items())
        assert heap.pop() == wanted
        del live[wanted[1]]
    assert heap.inspect()[0] == sorted((key, serial) for serial, (node, key) in live.items())
print("independent handle-map and Fibonacci-size checks:", 4000)
remaining = sorted((key, serial) for serial, (node, key) in live.items())
assert [heap.pop() for unused in range(len(live))] == remaining
assert heap.inspect() == ([], 0, 0)
print("drain and empty structure:", True)
heap = FibonacciHeap()
old = heap.insert(5)
heap.pop()
foreign = FibonacciHeap().insert(0)
current = heap.insert(1)
for action in (lambda: heap.decrease(old, 0), lambda: heap.decrease(foreign, -1),
               lambda: heap.decrease(current, 2), lambda: heap.insert(True)):
    try:
        action()
    except ValueError as error:
        print("rejected:", error)
    else:
        raise AssertionError("invalid operation accepted")

下面是这份程序的实际标准输出,不是需要另行执行的命令:

two nonroot ancestors marked: True True
cascading ancestor cuts in final decrease: 2
root count / marked count: (6, 0)
three new minima: [(-102, 15), (-101, 14), (-100, 10)]
independent handle-map and Fibonacci-size checks: 4000
drain and empty structure: True
rejected: live handle from this heap required
rejected: live handle from this heap required
rejected: new priority must not increase
rejected: bounded integer priority required

插入暂时不合并同度根

每个新节点直接作为零度根加入roots,同时更新minimum。即使根列表里已经有许多同度树,也不立即整理;真正弹出最小值时才统一合并。这是延后工作,而不是让森林失去堆序。

每个节点仍要求自己的优先级不大于孩子。priority用(key,serial)二元组比较,serial按插入顺序增长,所以相同key时有确定的先后。返回句柄指向节点身份,减键不会把身份换给别的值。

删除最小根,先释放它的孩子

pop移走minimum,把它的每个孩子改成根,并清除这些新根的mark。原节点标记为不再存活,随后调用方继续拿旧句柄减键会被拒绝。

根没有父亲,过去作为某个父亲孩子时的丢失记录已经结束,所以升为根必须清mark。以后它被重新链接到某个父亲下面,又从未丢失孩子的新阶段开始。

整理仍按相同度数链接,但树形不再固定

buckets按当前孩子数分组。同度根相遇时,优先级大的成为另一根的孩子,度数增加一,继续检查新的桶。所有链接完成后,根度数互异,再扫描剩余根得到新的minimum。

由于减键会切走部分子树,这里度数为d的节点不再恰好有2的d次方个后代。不能沿用二项树的精确形状断言;需要的是后文更宽松但仍指数增长的Fibonacci下界。

减键没有破坏父子顺序时,不要切断

decrease先验证新值没有增加,再修改节点key。若节点原本是根,或者新priority仍不小于父亲,就无需改变结构,只检查是否更新minimum。

若新priority小于父亲,cut从父亲的children字典移除该节点,将其加入roots并清mark。整个子树跟着节点搬走,后代之间的堆序并未改变,所以不需要逐个移动或重新插入后代。

第一次丢孩子标记,第二次丢孩子剪父亲

孩子被剪后,观察原父亲。如果它也是根,停止;如果它还连着祖父且没有mark,就设mark并停止;如果它已mark,说明这次是第二次丢失,要把它也剪下。

剪下已标记父亲之后,祖父也刚丢了一个孩子,继续执行相同规则。循环最终在某个未标记非根处留下一个新mark,或者到根为止;沿途被剪成根的旧mark全部清掉。

一个固定构造让两层级联真正发生

程序先插入0到64,再弹出零,形成经过同度整理的森林。随后选择一对有足够孩子、且都不是根的父子节点,先从上层剪走一个其他孩子,使上层mark为真,再从下层剪走一个孩子,使下层也有mark。

第三次减键再剪走下层另一个孩子,就同时触发下层和上层两个祖先切断。实际输出cascading ancestor cuts为二,结束后两者都是无mark的根,整个森林根数为六、标记数为零。

记号不是为了决定最小值,而是为了限制结构损耗

只要每条父子边仍满足堆序,即使完全不设置mark,弹出最小值也可能继续算对。但树的高度、度数和真实后代规模会慢慢失去足够约束,不能再得到同样的摊还保证。

mark记的是节点自从最近一次成为孩子之后是否已经失去一个孩子,不是访问标志、脏数据标志或优先级是否改变。直接修改公开的Node字段会绕过这些合同,句柄应只交给堆接口使用。

孩子度数的下界解释了Fibonacci这个名字

按加入时间排列一个节点目前仍保留的孩子,第i个孩子在当初链接时,度数至少为i减一;成为孩子之后最多再丢一位,否则它自己会被剪走。因此当前度数至少为i减二。

由此可推得度数为d的子树节点数至少是F(d+2),其中F(0)=0、F(1)=1。这个下界随d指数增长,所以n节点堆的最大度数为O(log n)。inspect从真实后代数重新检查这个下界,不使用缓存规模。

根数加两倍标记数,可以支付级联账单

用势能Φ=根数+2×已标记节点数理解摊还成本。剪掉一个已标记节点会增加一个根,但同时清掉一个值二的mark,势能净下降一,能够支付这次常数切断工作。

一次decrease最开始的直接切断和最后新产生的一个mark只增加常数量级势能,任意长的中间级联则由旧mark支付。因此减键是摊还O(1),并不是承诺每次调用都只切一条边。

弹出最小值的整理,也由以前留下的根支付

一次pop可能扫描很多根,真实耗时未必对数。但整理以后每种度数至多一根,而度数为对数量级;大量旧根消失带来的势能下降支付了大部分扫描与链接。

在常数时间指针操作的经典模型下,插入与减键摊还O(1),弹出最小值摊还O(log n)。本文用整数序号字典代替双向链表,沿用通常字典访问成本假设,不声称Python哈希表提供严格单次最坏常数保证。

独立句柄账本检查每次返回与每个结构

4000次混合操作使用一个普通字典单独保存serial与预期key。取最小用线性min,减键只改字典里对应数字;被测堆不从这个账本取排序信息。每步都比较所有存活节点的完整优先级集合。

inspect还检查父指针、所有权、存活标志、根不带mark、父子堆序、节点只出现一次及Fibonacci规模下界。最后全部弹空,核对剩余排序及空结构。跨堆句柄、已弹出句柄、增大优先级和布尔值另作拒绝测试。

句柄管理与接口范围要写清楚

owner把句柄绑定到创建它的堆;alive防止使用已经弹出的节点。当前最多1024个活节点,优先级绝对值不超过十亿。serial保持身份唯一,即使两个节点key相同也不能互换。

这份版本没有实现堆合并。经典Fibonacci堆可通过链表拼接快速合并,但本文字典及owner合同需要另外设计,不能直接拼接字典后继续声称所有句柄归属正确或合并为常数时间。

完整inspect会遍历全堆并排序,仅服务核验。本文没有进行与数组二叉堆的速度比较,实际运行性能还取决于对象、缓存与数据规模,不能由渐近摊还界直接推出。

参考资料

资料与运行核查日期:2026年10月7日。源码、解释及教学测试由本文独立组织;有限测试不等于生产性能评测。

David Karger MIT作者讲义:惰性整理、mark级联、双势能与Fibonacci度数界

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。