Chu–Liu有向生成树实战:每个点都选了最便宜入边,为什么还要按替换差额缩环

10-07 15阅读

在有向图里,让每个非根顶点都挑一条最便宜的入边,确实满足了每点一个父亲,却可能选出一个与根断开的环。直接删掉环上最贵边也不够:接入哪条外部边,决定了应当撤销哪一个点原来的父边。

本文实现Chu–Liu/Edmonds算法的最优成本版本,输出从指定根向外到达全部顶点的最小有向生成树成本,以及每轮减权和缩环轨迹。程序没有恢复最终原始边集合,因此成本正确与已经拿到可部署路线是两种交付。

Chu–Liu有向生成树实战:每个点都选了最便宜入边,为什么还要按替换差额缩环

AI模型生成的概念示意:外部根节点、环形连接与透明收拢环表达有向结构的成组处理;箭头与节点不对应正文精确图或执行轨迹。

完整程序与实际输出

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

from itertools import product
from random import Random


def arborescence_cost(n, root, edges):
    if (type(n) is not int or not 1 <= n <= 32 or type(root) is not int
            or not 0 <= root < n or type(edges) is not list or len(edges) > 4096):
        raise ValueError("bounded graph and valid integer root required")
    for edge in edges:
        if (type(edge) is not tuple or len(edge) != 3
                or any(type(x) is not int for x in edge)):
            raise ValueError("integer (tail, head, cost) entries required")
        u, v, cost = edge
        if not (0 <= u < n and 0 <= v < n and u != v and abs(cost) <= 10**6):
            raise ValueError("distinct endpoints and bounded integer costs required")
    edges = edges.copy()
    total, trace = 0, []
    while True:
        cheapest, parent = [None] * n, [-1] * n
        for u, v, cost in edges:
            if v != root and (cheapest[v] is None or cost < cheapest[v]):
                cheapest[v], parent[v] = cost, u
        cheapest[root] = 0
        if any(cost is None for cost in cheapest):
            return None, trace
        added = sum(cheapest)
        total += added
        component, visit = [-1] * n, [-1] * n
        cycles = []
        for start in range(n):
            v = start
            while v != root and component[v] == -1 and visit[v] != start:
                visit[v] = start
                v = parent[v]
            if v == root or component[v] != -1:
                continue
            cycle, w = [], v
            while True:
                component[w] = len(cycles)
                cycle.append(w)
                w = parent[w]
                if w == v:
                    break
            cycles.append(tuple(cycle))
        trace.append((n, added, tuple(cycles)))
        if not cycles:
            return total, trace
        count = len(cycles)
        for v in range(n):
            if component[v] == -1:
                component[v] = count
                count += 1
        edges = [(component[u], component[v], cost - cheapest[v])
                 for u, v, cost in edges if component[u] != component[v]]
        root, n = component[root], count


def exhaustive_cost(n, root, edges):
    targets = [v for v in range(n) if v != root]
    choices = [[edge for edge in edges if edge[1] == v] for v in targets]
    best = None
    for selected in product(*choices):
        outgoing = [[] for _ in range(n)]
        for u, v, cost in selected:
            outgoing[u].append(v)
        seen, todo = {root}, [root]
        while todo:
            for v in outgoing[todo.pop()]:
                if v not in seen:
                    seen.add(v)
                    todo.append(v)
        if len(seen) == n:
            cost = sum(edge[2] for edge in selected)
            best = cost if best is None else min(best, cost)
    return best


example = [(0, 1, 5), (0, 2, 6), (1, 2, 1), (2, 1, 1)]
value, trace = arborescence_cost(3, 0, example)
assert value == exhaustive_cost(3, 0, example) == 6
print("cycle example cost:", value)
print("rounds (vertices, added cost, cycles):", trace)
assert arborescence_cost(1, 0, [])[0] == 0
isolated = [(1, 2, -7), (2, 1, -9)]
assert arborescence_cost(3, 0, isolated)[0] is None
print("incoming edges exist, but root cannot reach:", arborescence_cost(3, 0, isolated)[0])
parallel = example + [(0, 1, 4)]
assert arborescence_cost(3, 0, parallel)[0] == 5
print("parallel alternative cost:", arborescence_cost(3, 0, parallel)[0])

possible = [(u, v) for u in range(3) for v in range(3) if u != v]
checked = 0
for weights in product((None, -1, 2), repeat=6):
    edges = [(u, v, w) for (u, v), w in zip(possible, weights) if w is not None]
    for root in range(3):
        assert arborescence_cost(3, root, edges)[0] == exhaustive_cost(3, root, edges)
        checked += 1
print("all three-vertex cases and roots:", checked)
rng, deepest = Random(6901), 0
for _ in range(600):
    n = rng.randrange(2, 7)
    root = rng.randrange(n)
    edges = [(u, v, rng.randrange(-5, 9)) for u in range(n) for v in range(n)
             if u != v and rng.randrange(3) == 0]
    value, trace = arborescence_cost(n, root, edges)
    assert value == exhaustive_cost(n, root, edges)
    deepest = max(deepest, len(trace))
assert deepest >= 3
print("random independent assignment comparisons:", 600)
print("maximum selection rounds observed:", deepest)
for args in [(0, 0, []), (2, True, []), (2, 0, [(0, 0, 1)]),
             (2, 0, [(0, 1, True)])]:
    try:
        arborescence_cost(*args)
    except ValueError as error:
        print("rejected:", error)
    else:
        raise AssertionError("invalid input accepted")

以下为这份程序的实际标准输出,不是需要再次执行的源码:

cycle example cost: 6
rounds (vertices, added cost, cycles): [(3, 2, ((1, 2),)), (2, 4, ())]
incoming edges exist, but root cannot reach: None
parallel alternative cost: 5
all three-vertex cases and roots: 2187
random independent assignment comparisons: 600
maximum selection rounds observed: 4
rejected: bounded graph and valid integer root required
rejected: bounded graph and valid integer root required
rejected: distinct endpoints and bounded integer costs required
rejected: integer (tail, head, cost) entries required

先固定方向:根向外,每个非根恰有一条入边

输入三元组(u,v,c)表示从u指向v,成本为c。合法答案覆盖全部顶点,根入度为零,其他顶点入度为一,而且从根能够到达每一个顶点。这样恰有n减一条边。

引用讲义采用所有点走向根、每个非根一条出边的约定。本文把全部方向反转,使用入边表述;减权所依据的端点也相应改为边的终点。若只改图上的箭头,却仍按起点扣减成本,账目便不再正确。

边权允许负数、零和并列;同一有向点对也允许平行边。输入检查拒绝自环、布尔值端点或权重、越界顶点,并限制最多32个点、4096条记录及每条成本绝对值不超过一百万。

最小入边给出一份所有答案共同支付的底价

对每个非根v,记最小入边成本为m[v]。任何合法树恰好用一条进入v的边,因此把每条u到v的成本改为c减m[v],会让所有合法树统一便宜sum(m)。谁更便宜的排序不会改变。

程序将这一轮sum(m)累加到total,再在剩余成本上求解。cheapest[root]人为设为零,进入根的边不参与最小入边选择;它们不会成为合法树的一部分。

如果某个非根连一条入边都没有,当前问题无解。这个检查既要在原图执行,也要在缩环后的图执行,因为一整团内部互指的点,可能各有入边却没有任何外部入口。

一个三点例子把替换差额完整列清

根为0,四条边是0到1成本5、0到2成本6、1到2成本1、2到1成本1。分别选择最便宜入边,会得到1与2互指的环,总底价为2。

把环缩为一团后,0到1的外部入口只需再付5减1等于4;0到2则需再付6减1等于5。选择额外成本4,总答案为2加4等于6,对应原图选0到1和1到2。

这个扣除的一来自被替换的2到1,不能因为环中另一条边恰好也重一就以为扣哪里都一样。一般各点最小入边不同,必须按外部边真正进入的点扣除。

选中父边组成函数图,沿父指针就能找环

每个非根已存一个parent。沿parent反向追踪,要么到根,要么进入一个已归组的环,要么在本轮起点的访问链中重复遇到同一顶点。最后一种情况才发现新环。

visit[v]存当前出发点编号,让不同起点的轨迹标记不混淆;component[v]只在真正环成员确定后填写。沿重复点继续追parent一圈,恰好收集这个环,不能把通向环的前缀一并收进去。

本轮可能存在几个互不相交的环,程序分别分配组件号,再给其余单点各分配一个号。多个不相交零成本环可以依次收缩,也可以像这里一样统一构造下一张图。

只保留跨组边,但暂不合并平行候选

下一轮边端点换成component[u]和component[v];同组内部边消失,跨组边成本换成c减cheapest[v]。这个公式也应用于仍是单点的目标,因为这一轮已经把它的底价加入total。

缩环产生的平行边在本实现中全都保留。下一轮选择最小入边时自然挑更便宜者,因此无需另写去重结构;若以后恢复原始边,还需要记录每条候选的来源身份。

新根是旧根所在的组件。根从不参加所选父边的环,不能随便把一个环编号当成新根。每次存在环就严格减少顶点数,所以这份迭代终会停止。

零成本环为什么可以先整体决定入口

减权以后,选中的环边成本全为零。假设较小图选择一条外部边进入这个环,展开时就删除它所进入顶点的那条环内父边,保留环上其余边;从入口沿原方向即可覆盖整个环,额外零边不改变剩余成本。

反过来,原图合法树进入环区域后,可以在收缩图中保留一份根可达的生成结构。剩余成本非负,删去多余边不会变得更贵。这给出两边最优成本相等的依据;并非所有随便挑出的环都允许按原权重直接收缩。

原始负边仍然允许,因为减去每个目标的最小入边后,所有可能被选择的非根入边都非负。进入根的边不参与树,也不会影响这份比较。

无环时,局部最小已经拼成全局答案

如果每个非根都有父边且不存在有向环,那么沿父指针不能永远停在非根区域,只能最终走到唯一没有父边的根。反转追踪方向,即得到根到每个点的路径。

因此此时选边本身就是合法有向树,并达到这一轮逐点底价。程序立即返回累计total。只有一个根顶点且没有边时,同样返回零,空的选择就是合法树。

演示中的孤立环1到2成本负七、2到1成本负九最初通过逐点入边检查,但收缩后没有来自根的入边,最终返回None。把它报告成负十六的树,会把便宜的不可行结构误当答案。

独立裁判枚举父边组合,再从根检查可达

exhaustive_cost为每个非根列出所有原始入边,枚举笛卡尔积。对每份选择重新构造正向邻接表,从根做可达性搜索;只有覆盖全部顶点才计算总成本并参加最小值比较。

裁判不减权、不缩环,也不利用parent访问编号;它直接按答案定义验证。这能发现减错端点、错误收缩前缀或忘记缩后无入口检查等问题。

三个顶点的六条可能有向边,各取不存在、成本负一、成本二,共729张图,再遍历三个根,总计2187组完整对照。另有600张二到六点随机图,实际观察到最多四轮选边,覆盖连续多次收缩情形。

平行边样本额外加入0到1成本4,答案从6降为5。非法输入也逐项确认抛出ValueError。有限枚举验证实现,不替代算法对一般输入的证明。

诊断版本的成本和交付边界

每轮扫描边表选择入边并重建跨组边需要O(E)。当前找环写法可能从多个起点重复经过尚未归组的父链,按O(V²)的宽松界计;最多O(V)轮,整个教学实现采用O(VE加V³)上界。它没有宣称实现讲义中精细遍历的O(VE)版本。

当前边表、工作数组和累计环轨迹占O(E加V²)的宽松空间界。穷举裁判的组合数量会迅速增长,只服务于小图测试,不在实际算法内部调用。

trace中的顶点编号属于各轮新图,不能直接拿第二轮编号回查原始业务节点。若下游需要具体边集合,必须增加跨层边身份、展开时被替换父边以及原顶点映射;这里明确只交付最优成本。

参考资料

资料核对与本地实跑日期:2026年10月7日。解释、程序和教学样本独立组织;有限测试不代表生产性能评测。

CMU高级算法原创讲义:Arborescences,减权与零成本环收缩

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