Python与SQLite精确求有向最小生成树:环收缩、原始边重建与回放验证

10-20 4阅读

给定一个广播源,怎样在带方向、可能含负权与平行边的网络中,精确选出费用最小的覆盖树?本文从可达性检查开始,实现 Chu–Liu/Edmonds 环收缩、嵌套展开、原始边编号证书与 SQLite 回放。九段代码只依赖 Python 标准库,每段均可独立运行,输出列在代码之后。

Python与SQLite精确求有向最小生成树:环收缩、原始边重建与回放验证
AI概念图:根向外传播、环收缩与分支展开的视觉隐喻,不作为算法拓扑或结果证明。

1.先固定有向模型,再用 SQLite 检查根可达性

把城市之间的连接费用存进数据库时,最容易犯的错误是把有向边当成无向边。这里的目标是一棵从给定根向外展开的覆盖树:根的入度为零,其余顶点各有一条入边,而且根必须沿所选边到达所有顶点。我们优化的是所选边权之和,不是每个顶点到根的最短路径长度之和,也不允许只覆盖一个便宜的连通分量。

先声明数据契约:顶点、原始边编号和权重均为整数;原始编号唯一;允许平行边与负权,输入中的自环和指向根的边不参与候选。平行边不能按起终点去重,因为它们可能代表不同供应商或不同可追溯记录。顶点表也不能省略,否则没有任何关联边的孤立顶点会从任务中消失。

下面用递归公共表表达式求可达集合。UNION 会消除已经出现的顶点,因此即使数据里有环也能结束;最后的 ORDER BY 是输出顺序契约。若根不能到达全部顶点,任何选择算法都无法生成要求的树。反过来,沿根的搜索树保留首次到达边,就给出了可行树的存在性。这个检查比仅统计每个顶点有没有入边更强。SQLite 官方 WITH 文档说明了递归查询与去重语义。

import sqlite3
con = sqlite3.connect(':memory:')
con.execute('PRAGMA foreign_keys = ON')
con.executescript("""
CREATE TABLE vertex(v INTEGER PRIMARY KEY);
CREATE TABLE edge(
  id INTEGER PRIMARY KEY,
  u INTEGER NOT NULL REFERENCES vertex(v),
  v INTEGER NOT NULL REFERENCES vertex(v),
  w INTEGER NOT NULL CHECK(typeof(w) = 'integer')
);
""")
con.executemany('INSERT INTO vertex VALUES (?)', [(0,), (1,), (2,), (3,)])
con.executemany('INSERT INTO edge VALUES (?,?,?,?)',
                [(1, 0, 1, 8), (2, 1, 2, -2), (3, 2, 1, -1)])
reachable = [row[0] for row in con.execute("""
WITH RECURSIVE reach(v) AS (
  VALUES (?) UNION
  SELECT e.v FROM edge e JOIN reach r ON e.u = r.v
)
SELECT v FROM reach ORDER BY v
""", (0,))]
print('reachable:', reachable)
print('missing:', sorted({0, 1, 2, 3} - set(reachable)))
con.close()

运行输出:

reachable: [0, 1, 2]
missing: [3]

这里顶点三不可达,必须报告无解,不能把它悄悄删掉。INTEGER 列的类型亲和性并不等同于严格的输入类型检查;本例加上存储类型约束,求解器还会验证 Python 值。若原始接口要拒绝数字字符串,应在写入前检查,而不是等 SQLite 完成类型转换后再猜输入是什么。

2.逐点选最便宜入边,为什么仍会失败

如果暂时忽略全局可达性,每个非根顶点都可以独立选择最便宜的入边。这给出了一个自然的成本下界,却不保证得到树。下面两个负权边互相指向,虽然每个非根顶点都满足入度一,根却没有任何通路进入它们。无向最小生成树中的并查集贪心也不能直接替代这里的处理,因为它维护的约束没有表达每个顶点唯一的入边方向。

本篇统一以当前权重、原始边编号组成的二元组比较边。权重相同就选较小编号;顶点遍历也排序。这样数据库返回行的顺序、集合内部排列及调用者传入顺序都不会影响结果。需要强调,这只是确定性规则,不承诺所有最优树里面,最终编号列表在字典序上最小。

edges = [(1, 0, 1, 8), (2, 0, 2, 9),
         (3, 1, 2, -2), (4, 2, 1, -1)]
incoming = {v: min((e for e in edges if e[2] == v),
                   key=lambda e: (e[3], e[0])) for v in (1, 2)}
print('greedy IDs:', sorted(e[0] for e in incoming.values()))
print('lower bound:', sum(e[3] for e in incoming.values()))
print('parents:', [(v, incoming[v][1]) for v in sorted(incoming)])

运行输出:

greedy IDs: [3, 4]
lower bound: -3
parents: [(1, 2), (2, 1)]

3.进入环的边,要减去被替换的那条边

设已经选出的入边形成有向环。把整个环缩成一个超点,内部边暂时移除,离开环的边只改变起点,进入环的边则要重新计价。若外部边进入原顶点 v,它最终会替换 v 原本选中的那条环边,所以缩图费用是外部边权减去该环边权。注意减的是目标顶点对应的入边,既不是环上最小权,也不是全环总权。

展开时把环内原先选中的边补回,只删除被外部进入边替换的那一条。于是原图的展开成本,恰好等于缩图成本加上环内全部已选入边的成本。这个固定偏移量不依赖选择哪条进入边,因此可以在缩图继续优化。下面两种入口的原始费用与被替换的环边都不同,必须比较调整后的费用;负数没有任何特殊分支,整数加减足以保持精确。

cycle_in = {1: (4, 2, 1, -1), 2: (3, 1, 2, -2)}
entrances = [(1, 0, 1, 8), (2, 0, 2, 9)]
base = sum(e[3] for e in cycle_in.values())
for edge_id, u, v, w in entrances:
    reduced = w - cycle_in[v][3]
    expanded = w + sum(e[3] for x, e in cycle_in.items() if x != v)
    assert expanded == base + reduced
    print(edge_id, 'reduced:', reduced, 'expanded:', expanded)

运行输出:

1 reduced: 9 expanded: 6
2 reduced: 11 expanded: 8

严格的正确性还需要交换论证:任意可行树都必须从外部进入这个不含根的环;取从根首次进入环的边,再把其余环顶点的入边替换为已经选出的最小入边,不会增加成本,并能沿断开的环到达所有环顶点。由此存在最优解只保留一个环入口,才可以与缩图树对应。仅有成本等式还不足以证明全局最优。

4.完整精确求解器,连嵌套环一起展开

下面给出完整实现。代码采用一次收缩一个环的递归结构,优先清晰地保留来源信息。边始终携带原始编号;每一层都保留该层的端点与调整后权重,递归只返回所选原始编号集合。展开时用这一层的边表查入口,避免把深层超点误当成原始顶点。新的超点编号取当前最大顶点加一,日志中的超点只在对应层有意义。

本例先收缩顶点一和二,再发现它们组成的超点与顶点三形成新环。日志按实际展开顺序输出,所以深层事件在前。进入边、删除边与恢复边全部使用原始编号;环字段使用当前层顶点编号。编号八的自环与编号九的根入边无论多便宜都被忽略,编号一与七则是保留下来的平行候选。最终重新对原始权重求和,绝不能把调整后的权重直接当作业务账单。

这个实现属于 Chu–Liu/Edmonds 的直接收缩路线。Chu 与 Liu 的原始论文给出有向树收缩思想;Edmonds 的原始论文讨论指定根的最优有向树与逆序展开。本文的输入契约、编号追踪和测试代码是围绕可回放实现重新组织的示例。

def arborescence(vertices, root, edges):
    nodes, rows = list(vertices), [tuple(e) for e in edges]
    if (any(type(v) is not int for v in nodes)
            or len(set(nodes)) != len(nodes) or root not in nodes
            or type(root) is not int):
        raise ValueError('bad vertices or root')
    V = set(nodes)
    if (any(len(e) != 4 or any(type(x) is not int for x in e)
            for e in rows) or len({e[0] for e in rows}) != len(rows)):
        raise ValueError('bad edges or duplicate IDs')
    if any(u not in V or v not in V for _, u, v, _ in rows):
        raise ValueError('unknown endpoint')
    E = [e for e in rows if e[1] != e[2] and e[2] != root]
    reached = {root}
    while True:
        more = reached | {v for _, u, v, _ in E if u in reached}
        if more == reached:
            break
        reached = more
    if reached != V:
        raise ValueError('root cannot reach all vertices')
    trace = []

    def solve(V, E, level):
        incoming = {}
        for e in E:
            i, u, v, w = e
            if v not in incoming or (w, i) < (incoming[v][3], incoming[v][0]):
                incoming[v] = e
        cycle = None
        done = {root}
        for start in sorted(V):
            path, where, v = [], {}, start
            while v not in done and v not in where:
                where[v] = len(path)
                path.append(v)
                v = incoming[v][1]
            if v in where:
                cycle = set(path[where[v]:])
                break
            done.update(path)
        if cycle is None:
            return {e[0] for e in incoming.values()}
        supernode = max(V) + 1
        reduced = []
        for i, u, v, w in E:
            a = supernode if u in cycle else u
            b = supernode if v in cycle else v
            if a == b:
                continue
            if v in cycle and u not in cycle:
                w -= incoming[v][3]
            reduced.append((i, a, b, w))
        chosen = solve((V - cycle) | {supernode}, reduced, level + 1)
        entering = [e for e in E if e[0] in chosen
                    and e[1] not in cycle and e[2] in cycle]
        assert len(entering) == 1
        entry = entering[0]
        restored = {incoming[v][0] for v in cycle if v != entry[2]}
        trace.append({'level': level, 'cycle': sorted(cycle),
                      'enter': entry[0], 'drop': incoming[entry[2]][0],
                      'restore': sorted(restored)})
        return chosen | restored

    ids = sorted(solve(V, E, 0))
    original = {e[0]: e for e in rows}
    return {'ids': ids, 'cost': sum(original[i][3] for i in ids), 'trace': trace}

edges = [(1, 0, 1, 10), (2, 0, 3, 10), (3, 1, 2, -3),
          (4, 2, 1, -3), (5, 2, 3, 1), (6, 3, 1, 1),
          (7, 0, 1, 10), (8, 2, 2, -100), (9, 3, 0, -999),
          (10, 0, 2, 30)]

answer = arborescence(range(4), 0, edges)
print('IDs:', answer['ids'], 'cost:', answer['cost'])
for step in answer['trace']:
    print(step)

运行输出:

IDs: [1, 3, 5] cost: 8
{'level': 1, 'cycle': [3, 4], 'enter': 1, 'drop': 6, 'restore': [5]}
{'level': 0, 'cycle': [1, 2], 'enter': 1, 'drop': 4, 'restore': [3]}

根永远不会进入所选入边形成的环,因此收缩时根编号不需要变化。根可达性在收缩后保持成立,每个当前非根顶点都有候选入边。没有环时,全部最小入边已经构成覆盖树;有环时继续递归,顶点数严格减少。这也解释了单顶点图为何返回空边集与零成本。

5.独立核对结构与逐层展开证书

求解函数成功返回,并不意味着调用者可以省略独立验收。结构检查至少应确认边编号存在且不重复、边数等于顶点数减一、根入度为零、其余顶点入度为一,以及根在结果图上能到达全部顶点。只检查入度会放过互相指向的孤立环;只检查边数会放过很多不连通的组合。

下面先检查原始编号的可行性,再用单独编写的 audit 根据日志从外到内重建缩图,检查无环的叶层,最后逆序展开。它重新计算每层最小入边,核对进入边、删除边、恢复边和原始总成本,不调用待测求解器。日志并不能脱离输入证明最优性;这里的完整回放加上前述收缩论证,才说明结果遵守了求解规则。对小图还要用下一节的独立穷举器核对最优值。

def feasible(vertices, root, edges, ids):
    V, chosen_ids = set(vertices), list(ids)
    index = {i: (u, v, w) for i, u, v, w in edges}
    if root not in V or len(chosen_ids) != len(V) - 1:
        return False
    if len(set(chosen_ids)) != len(chosen_ids):
        return False
    if any(i not in index for i in chosen_ids):
        return False
    selected = [index[i] for i in chosen_ids]
    indegree = {v: 0 for v in V}
    for u, v, _ in selected:
        if u not in V or v not in V or u == v:
            return False
        indegree[v] += 1
    if any(indegree[v] != (v != root) for v in V):
        return False
    reached = {root}
    while True:
        more = reached | {v for u, v, _ in selected if u in reached}
        if more == reached:
            return reached == V
        reached = more

# An independently structured checker for the recorded reconstruction steps.
def audit(vertices, root, edges, answer):
    V = set(vertices)
    E = {i: (u, v, w) for i, u, v, w in edges if u != v and v != root}
    snapshots = []
    events = sorted(answer['trace'], key=lambda x: x['level'])
    assert [e['level'] for e in events] == list(range(len(events)))
    for record in events:
        C = set(record['cycle'])
        assert len(C) == len(record['cycle']) and len(C) >= 2
        assert C <= V and root not in C
        parent = {}
        for v in V - {root}:
            parent[v] = min((i for i, e in E.items() if e[1] == v),
                            key=lambda i: (E[i][2], i))
        assert {E[parent[v]][0] for v in C} == C
        cursor = next(iter(C))
        walked = set()
        while cursor not in walked:
            walked.add(cursor)
            cursor = E[parent[cursor]][0]
        assert walked == C
        snapshots.append((E, parent, C, record))
        q = max(V) + 1
        contracted = {}
        for i, (u, v, w) in E.items():
            a, b = (q if u in C else u), (q if v in C else v)
            if a != b:
                if v in C:
                    w -= E[parent[v]][2]
                contracted[i] = (a, b, w)
        E = contracted
        V = (V - C) | {q}
    selected = set()
    for v in V - {root}:
        selected.add(min((i for i, e in E.items() if e[1] == v),
                         key=lambda i: (E[i][2], i)))
    leaf = [(i, *E[i]) for i in E]
    assert feasible(V, root, leaf, selected)
    for old_edges, parent, C, record in reversed(snapshots):
        entrances = [i for i in selected if old_edges[i][0] not in C
                     and old_edges[i][1] in C]
        assert len(entrances) == 1 and entrances[0] == record['enter']
        target = old_edges[entrances[0]][1]
        assert parent[target] == record['drop']
        restored = sorted(parent[v] for v in C - {target})
        assert restored == record['restore']
        selected.update(restored)
    assert sorted(selected) == answer['ids']
    original = {e[0]: e for e in edges}
    assert sum(original[i][3] for i in selected) == answer['cost']
    assert feasible(vertices, root, edges, selected)
    return True

edges = [(1, 0, 1, 10), (2, 0, 3, 10), (3, 1, 2, -3),
          (4, 2, 1, -3), (5, 2, 3, 1), (6, 3, 1, 1),
          (7, 0, 1, 10), (8, 2, 2, -100), (9, 3, 0, -999),
          (10, 0, 2, 30)]

for ids in ([1, 3, 5], [3, 4, 5], [1, 1, 5]):
    print(ids, feasible(range(4), 0, edges, ids))
certificate = {'ids': [1, 3, 5], 'cost': 8, 'trace': [
    {'level': 1, 'cycle': [3, 4], 'enter': 1, 'drop': 6, 'restore': [5]},
    {'level': 0, 'cycle': [1, 2], 'enter': 1, 'drop': 4, 'restore': [3]}]}
print('reconstruction:', audit(range(4), 0, edges, certificate))
certificate['trace'][0]['drop'] = 999
try:
    audit(range(4), 0, edges, certificate)
except AssertionError:
    print('tampered certificate: rejected')

运行输出:

[1, 3, 5] True
[3, 4, 5] False
[1, 1, 5] False
reconstruction: True
tampered certificate: rejected

校验代码使用断言作为教学验收机制,运行时不要开启会移除断言的 Python 优化模式。面向不可信输入的生产接口应改为显式校验异常,并限制日志大小、层数与计算资源。

6.枚举每个非根顶点的入边,建立精确对照

测试最容易自欺的方式,是用另一个外形不同、实际上共享相同收缩错误的实现做参照。这里采用完全不同的办法:为每个非根顶点建立入边候选桶,枚举这些桶的笛卡尔积,再逐个检查根可达性。所有合法树都恰好包含在这种枚举中,不需要枚举所有边子集,也没有使用待测算法的中间结论。

枚举器返回最低成本与一个用于自身稳定输出的编号列表。并列时它选择字典序最小列表,而收缩器使用逐层局部并列规则,因此对照测试只要求最优成本一致,并独立验证收缩器输出的可行性,不能强求两个编号列表总相同。没有可行组合时返回 None;单顶点的空笛卡尔积包含一个空选择,成本自然为零。

from itertools import product


def oracle(vertices, root, edges):
    V = set(vertices)
    buckets = [[e for e in edges if e[2] == v and e[1] != v]
               for v in sorted(V - {root})]
    best = None
    for assignment in product(*buckets):
        reached = {root}
        while True:
            more = reached | {v for _, u, v, _ in assignment if u in reached}
            if more == reached:
                break
            reached = more
        if reached != V:
            continue
        candidate = (sum(e[3] for e in assignment),
                     tuple(sorted(e[0] for e in assignment)))
        if best is None or candidate < best:
            best = candidate
    return best

edges = [(1, 0, 1, 10), (2, 0, 3, 10), (3, 1, 2, -3),
          (4, 2, 1, -3), (5, 2, 3, 1), (6, 3, 1, 1),
          (7, 0, 1, 10), (8, 2, 2, -100), (9, 3, 0, -999),
          (10, 0, 2, 30)]

print('oracle:', oracle(range(4), 0, edges))
print('unreachable:', oracle(range(3), 0, [(1, 1, 2, -4)]))
print('singleton:', oracle([0], 0, []))

运行输出:

oracle: (8, (1, 3, 5))
unreachable: None
singleton: (0, ())

它的枚举量等于各非根顶点有效入度的乘积,指数增长是刻意接受的代价。这个工具适合小规模测试和反例缩减,不适合替代正式求解器。平行边必须各占一个候选位置,负权也不能用提前停止或未经证明的剪枝略过。

7.顺序扰动与并列边,结果仍然可复现

数据库查询若没有明确排序,不应依赖其碰巧稳定的返回顺序。求解器本身也应消除这类隐式依赖。下面把同一份数据的行顺序反转,并反转顶点输入顺序,结果必须完全相同,包括展开日志。随后使用两条同端点、同权重的边检查原始编号决胜,较小编号会被保留。

为了让每个示例都可以复制后单独运行,本节和后面的回放、随机对照会重复完整求解器。正式项目可以将其放进一个模块,并把版本标识与输入快照一起保存。不要为了让代码更短就把编号改成列表下标,否则插入一条无关记录也可能改变并列结果,审计日志很难长期解释。

def arborescence(vertices, root, edges):
    nodes, rows = list(vertices), [tuple(e) for e in edges]
    if (any(type(v) is not int for v in nodes)
            or len(set(nodes)) != len(nodes) or root not in nodes
            or type(root) is not int):
        raise ValueError('bad vertices or root')
    V = set(nodes)
    if (any(len(e) != 4 or any(type(x) is not int for x in e)
            for e in rows) or len({e[0] for e in rows}) != len(rows)):
        raise ValueError('bad edges or duplicate IDs')
    if any(u not in V or v not in V for _, u, v, _ in rows):
        raise ValueError('unknown endpoint')
    E = [e for e in rows if e[1] != e[2] and e[2] != root]
    reached = {root}
    while True:
        more = reached | {v for _, u, v, _ in E if u in reached}
        if more == reached:
            break
        reached = more
    if reached != V:
        raise ValueError('root cannot reach all vertices')
    trace = []

    def solve(V, E, level):
        incoming = {}
        for e in E:
            i, u, v, w = e
            if v not in incoming or (w, i) < (incoming[v][3], incoming[v][0]):
                incoming[v] = e
        cycle = None
        done = {root}
        for start in sorted(V):
            path, where, v = [], {}, start
            while v not in done and v not in where:
                where[v] = len(path)
                path.append(v)
                v = incoming[v][1]
            if v in where:
                cycle = set(path[where[v]:])
                break
            done.update(path)
        if cycle is None:
            return {e[0] for e in incoming.values()}
        supernode = max(V) + 1
        reduced = []
        for i, u, v, w in E:
            a = supernode if u in cycle else u
            b = supernode if v in cycle else v
            if a == b:
                continue
            if v in cycle and u not in cycle:
                w -= incoming[v][3]
            reduced.append((i, a, b, w))
        chosen = solve((V - cycle) | {supernode}, reduced, level + 1)
        entering = [e for e in E if e[0] in chosen
                    and e[1] not in cycle and e[2] in cycle]
        assert len(entering) == 1
        entry = entering[0]
        restored = {incoming[v][0] for v in cycle if v != entry[2]}
        trace.append({'level': level, 'cycle': sorted(cycle),
                      'enter': entry[0], 'drop': incoming[entry[2]][0],
                      'restore': sorted(restored)})
        return chosen | restored

    ids = sorted(solve(V, E, 0))
    original = {e[0]: e for e in rows}
    return {'ids': ids, 'cost': sum(original[i][3] for i in ids), 'trace': trace}

edges = [(1, 0, 1, 10), (2, 0, 3, 10), (3, 1, 2, -3),
          (4, 2, 1, -3), (5, 2, 3, 1), (6, 3, 1, 1),
          (7, 0, 1, 10), (8, 2, 2, -100), (9, 3, 0, -999),
          (10, 0, 2, 30)]

a = arborescence(range(4), 0, edges)
b = arborescence([3, 2, 1, 0], 0, list(reversed(edges)))
assert a == b
print('order invariant:', a == b)
parallel = [(20, 0, 1, -4), (10, 0, 1, -4)]
print('parallel:', arborescence([0, 1], 0, parallel)['ids'])
print('singleton:', arborescence([0], 0, []))

运行输出:

order invariant: True
parallel: [10]
singleton: {'ids': [], 'cost': 0, 'trace': []}

8.SQLite 保存快照、编号结果与展开日志

落库时要区分业务边、某次运行的输入和运行结果。以下演示在一个事务中保存顶点快照、全部原始边,以及根、求解器版本、输入摘要、所选编号、总成本与展开日志。提交后关闭连接,再从磁盘重新打开,按固定顺序重建输入并复算。回放比较整个结果对象,因此既检查总价,也检查编号与展开过程。

摘要采用固定 JSON 编码,只用于发现意外改动,并不提供数字签名那样的防篡改保证。所有 SQL 值都通过占位符绑定。SQLite 的整数存储有范围限制,而 Python 整数可以继续增长;本例将计算后的总成本和日志置于 JSON 文本,避免对原始边做 SQL SUM 时误把数据库整数溢出当成算法问题。实际输入边权仍须在 SQLite 可表示的范围内。SQLite 类型文档与Python sqlite3 文档提供类型、参数绑定和连接管理依据。

def arborescence(vertices, root, edges):
    nodes, rows = list(vertices), [tuple(e) for e in edges]
    if (any(type(v) is not int for v in nodes)
            or len(set(nodes)) != len(nodes) or root not in nodes
            or type(root) is not int):
        raise ValueError('bad vertices or root')
    V = set(nodes)
    if (any(len(e) != 4 or any(type(x) is not int for x in e)
            for e in rows) or len({e[0] for e in rows}) != len(rows)):
        raise ValueError('bad edges or duplicate IDs')
    if any(u not in V or v not in V for _, u, v, _ in rows):
        raise ValueError('unknown endpoint')
    E = [e for e in rows if e[1] != e[2] and e[2] != root]
    reached = {root}
    while True:
        more = reached | {v for _, u, v, _ in E if u in reached}
        if more == reached:
            break
        reached = more
    if reached != V:
        raise ValueError('root cannot reach all vertices')
    trace = []

    def solve(V, E, level):
        incoming = {}
        for e in E:
            i, u, v, w = e
            if v not in incoming or (w, i) < (incoming[v][3], incoming[v][0]):
                incoming[v] = e
        cycle = None
        done = {root}
        for start in sorted(V):
            path, where, v = [], {}, start
            while v not in done and v not in where:
                where[v] = len(path)
                path.append(v)
                v = incoming[v][1]
            if v in where:
                cycle = set(path[where[v]:])
                break
            done.update(path)
        if cycle is None:
            return {e[0] for e in incoming.values()}
        supernode = max(V) + 1
        reduced = []
        for i, u, v, w in E:
            a = supernode if u in cycle else u
            b = supernode if v in cycle else v
            if a == b:
                continue
            if v in cycle and u not in cycle:
                w -= incoming[v][3]
            reduced.append((i, a, b, w))
        chosen = solve((V - cycle) | {supernode}, reduced, level + 1)
        entering = [e for e in E if e[0] in chosen
                    and e[1] not in cycle and e[2] in cycle]
        assert len(entering) == 1
        entry = entering[0]
        restored = {incoming[v][0] for v in cycle if v != entry[2]}
        trace.append({'level': level, 'cycle': sorted(cycle),
                      'enter': entry[0], 'drop': incoming[entry[2]][0],
                      'restore': sorted(restored)})
        return chosen | restored

    ids = sorted(solve(V, E, 0))
    original = {e[0]: e for e in rows}
    return {'ids': ids, 'cost': sum(original[i][3] for i in ids), 'trace': trace}

edges = [(1, 0, 1, 10), (2, 0, 3, 10), (3, 1, 2, -3),
          (4, 2, 1, -3), (5, 2, 3, 1), (6, 3, 1, 1),
          (7, 0, 1, 10), (8, 2, 2, -100), (9, 3, 0, -999),
          (10, 0, 2, 30)]

import hashlib
import json
import sqlite3
import tempfile
from pathlib import Path

def fingerprint(vertices, rows, root):
    payload = json.dumps([sorted(vertices), sorted(rows), root],
                         separators=(',', ':'))
    return hashlib.sha256(payload.encode()).hexdigest()

with tempfile.TemporaryDirectory() as directory:
    path = Path(directory) / 'audit.db'
    con = sqlite3.connect(path)
    con.executescript("""
    CREATE TABLE vertex(v INTEGER PRIMARY KEY);
    CREATE TABLE edge(id INTEGER PRIMARY KEY, u INTEGER, v INTEGER, w INTEGER);
    CREATE TABLE run(version TEXT, root INTEGER, digest TEXT, result TEXT);
    """)
    with con:
        con.executemany('INSERT INTO vertex VALUES (?)', [(v,) for v in range(4)])
        con.executemany('INSERT INTO edge VALUES (?,?,?,?)', edges)
        result = arborescence(range(4), 0, edges)
        con.execute('INSERT INTO run VALUES (?,?,?,?)',
                    ('cle-demo-1', 0, fingerprint(range(4), edges, 0),
                     json.dumps(result, sort_keys=True)))
    con.close()
    con = sqlite3.connect(path)
    vertices = [r[0] for r in con.execute('SELECT v FROM vertex ORDER BY v')]
    rows = list(con.execute('SELECT id,u,v,w FROM edge ORDER BY id'))
    version, root, digest, saved = con.execute('SELECT * FROM run').fetchone()
    assert version == 'cle-demo-1'
    assert digest == fingerprint(vertices, rows, root)
    replay = arborescence(vertices, root, rows)
    assert replay == json.loads(saved)
    print('snapshot:', len(vertices), len(rows))
    print('replay:', replay['ids'], replay['cost'])
    print('expansions:', len(replay['trace']))
    con.close()

运行输出:

snapshot: 4 10
replay: [1, 3, 5] 8
expansions: 2

这个临时数据库只服务于可复制演示,程序结束后会自动删除。生产审计应使用持久文件或独立运行表,以运行编号关联快照,禁止覆盖旧输入。如果另一个进程可能同时编辑源边表,应先在同一数据库事务中读出快照,再对该快照计算与保存,不能先后拼接不同时间点的两份数据。

9.用有界随机图反复挑战收缩与重建

最后把完整求解器与入边分配穷举器放进同一段独立程序。固定随机种子、限制每个非根顶点候选数,并加入可能的负权、平行边和自环。根到每个非根顶点有一条保底边,因此这些随机案例都可行;无解分支则由前面的孤立点示例和专项测试覆盖。每次既比较精确成本,也反转输入次序验证确定性。

正确性回归还应单独固定嵌套收缩、多个互不相交的环、超大整数、重复编号和非法端点,不能指望随机样本碰巧覆盖。下面的一百二十次通过只是明确可复现的测试结果,不是对任意程序正确性的数学证明。实现的正确性依靠收缩与展开的对应关系,测试用来发现实现没有遵守该关系的地方。

def arborescence(vertices, root, edges):
    nodes, rows = list(vertices), [tuple(e) for e in edges]
    if (any(type(v) is not int for v in nodes)
            or len(set(nodes)) != len(nodes) or root not in nodes
            or type(root) is not int):
        raise ValueError('bad vertices or root')
    V = set(nodes)
    if (any(len(e) != 4 or any(type(x) is not int for x in e)
            for e in rows) or len({e[0] for e in rows}) != len(rows)):
        raise ValueError('bad edges or duplicate IDs')
    if any(u not in V or v not in V for _, u, v, _ in rows):
        raise ValueError('unknown endpoint')
    E = [e for e in rows if e[1] != e[2] and e[2] != root]
    reached = {root}
    while True:
        more = reached | {v for _, u, v, _ in E if u in reached}
        if more == reached:
            break
        reached = more
    if reached != V:
        raise ValueError('root cannot reach all vertices')
    trace = []

    def solve(V, E, level):
        incoming = {}
        for e in E:
            i, u, v, w = e
            if v not in incoming or (w, i) < (incoming[v][3], incoming[v][0]):
                incoming[v] = e
        cycle = None
        done = {root}
        for start in sorted(V):
            path, where, v = [], {}, start
            while v not in done and v not in where:
                where[v] = len(path)
                path.append(v)
                v = incoming[v][1]
            if v in where:
                cycle = set(path[where[v]:])
                break
            done.update(path)
        if cycle is None:
            return {e[0] for e in incoming.values()}
        supernode = max(V) + 1
        reduced = []
        for i, u, v, w in E:
            a = supernode if u in cycle else u
            b = supernode if v in cycle else v
            if a == b:
                continue
            if v in cycle and u not in cycle:
                w -= incoming[v][3]
            reduced.append((i, a, b, w))
        chosen = solve((V - cycle) | {supernode}, reduced, level + 1)
        entering = [e for e in E if e[0] in chosen
                    and e[1] not in cycle and e[2] in cycle]
        assert len(entering) == 1
        entry = entering[0]
        restored = {incoming[v][0] for v in cycle if v != entry[2]}
        trace.append({'level': level, 'cycle': sorted(cycle),
                      'enter': entry[0], 'drop': incoming[entry[2]][0],
                      'restore': sorted(restored)})
        return chosen | restored

    ids = sorted(solve(V, E, 0))
    original = {e[0]: e for e in rows}
    return {'ids': ids, 'cost': sum(original[i][3] for i in ids), 'trace': trace}

from itertools import product


def oracle(vertices, root, edges):
    V = set(vertices)
    buckets = [[e for e in edges if e[2] == v and e[1] != v]
               for v in sorted(V - {root})]
    best = None
    for assignment in product(*buckets):
        reached = {root}
        while True:
            more = reached | {v for _, u, v, _ in assignment if u in reached}
            if more == reached:
                break
            reached = more
        if reached != V:
            continue
        candidate = (sum(e[3] for e in assignment),
                     tuple(sorted(e[0] for e in assignment)))
        if best is None or candidate < best:
            best = candidate
    return best

def feasible(vertices, root, edges, ids):
    V, chosen_ids = set(vertices), list(ids)
    index = {i: (u, v, w) for i, u, v, w in edges}
    if root not in V or len(chosen_ids) != len(V) - 1:
        return False
    if len(set(chosen_ids)) != len(chosen_ids):
        return False
    if any(i not in index for i in chosen_ids):
        return False
    selected = [index[i] for i in chosen_ids]
    indegree = {v: 0 for v in V}
    for u, v, _ in selected:
        if u not in V or v not in V or u == v:
            return False
        indegree[v] += 1
    if any(indegree[v] != (v != root) for v in V):
        return False
    reached = {root}
    while True:
        more = reached | {v for u, v, _ in selected if u in reached}
        if more == reached:
            return reached == V
        reached = more

import random
rng = random.Random(20261020)
for case in range(120):
    n = rng.randrange(1, 6)
    rows = []
    for v in range(1, n):
        rows.append((len(rows) + 1, 0, v, rng.randrange(-7, 8)))
        for _ in range(rng.randrange(3)):
            rows.append((len(rows) + 1, rng.randrange(n), v,
                         rng.randrange(-7, 8)))
    result = arborescence(range(n), 0, rows)
    expected = oracle(range(n), 0, rows)
    assert expected is not None and result['cost'] == expected[0]
    assert feasible(range(n), 0, rows, result['ids'])
    assert result == arborescence(range(n), 0, list(reversed(rows)))
print('exact oracle cases:', 120)
print('status: PASS')

运行输出:

exact oracle cases: 120
status: PASS

这个教学实现每层扫描边并寻找一个环,最多进行与顶点数同阶的收缩;排序和整数位数成本也必须考虑,不能把它宣传成高级数据结构版本的近线性实现。递归深度、重复保留边表和日志占用限制了它对超大图的适用性。处理大规模生产任务时,应先依据实际输入分布测量时间与内存,再选择迭代展开或更高效的成熟实现,同时保留这里的原始编号、精确费用和回放验收契约。

最终交付的重点不是一个最小总价数字,而是能够解释每条边来自哪里、哪个环被收缩、入口替换了哪条边,以及相同快照是否得到相同结果。把方向约束放进模型,把整数算术放进求解,把独立穷举放进测试,把快照放进 SQLite,才能让有向最小生成树从一次演示变成可核验的工程组件。

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