Python 与 SQLite 实现 Gomory-Hu 树:两点最小割查询与可验证割证书

10-20 4阅读

同一张无向网络上,如果业务不断询问任意两个节点至少要切断多少总容量才能分离,每次重新运行最大流会重复做大量工作。Gomory-Hu 树把所有不同顶点对的最小割信息压缩为一棵加权树:沿树上唯一通路取最小边权,就能读出答案。真正有价值的地方还包括恢复一个能在原图上逐边核验的最小割分区。

本文使用 Python 标准库与 SQLite,容量限定为非负整数,重点讲父节点更新、旋转、查询证书与持久化边界。九个示例都可以分别复制成脚本直接运行,无需安装第三方包,也不依赖前一段创建的变量或文件。测试环境为 Python 3.12,数据库示例使用内存连接;代码为了教学透明保留了重复函数,实际工程可抽成一个经过测试的模块。

Python 与 SQLite 实现 Gomory-Hu 树:两点最小割查询与可验证割证书
AI概念图:从容量网络到割树与数据库索引。插画仅表达主题,不对应示例的具体顶点与边。

先确定我们承诺回答什么

只讨论无向边容量的 s-t 最小割,不讨论顶点删除代价、有向网络或任意多个终端的最小割。对相同顶点发起查询没有通常意义上的分离问题,接口直接报错,不返回零或随意选择一个无穷大。若两端本来就不连通,正确答案为零;这与输入缺失、查询失败以及空图不是一回事。

经典割树能够保存两点值及对应的最小割分区;仅仅让所有路径瓶颈数值正确,还不足以保证任意瓶颈边的分区正确。Gusfield 与 Naor 的原始研究论文明确区分这两个概念。下面既构造割树,也故意制造一个只能答对数值的反例。

示例一:把无向容量写成可复查的输入快照

先固定输入契约。顶点使用从零开始的连续整数编号,顶点表必须显式保存孤立点;边按较小端点、较大端点排序,平行边在 Python 中求和。自环不会跨越任何割,本教程直接拒绝,以便尽早暴露上游数据问题。零容量边允许存在,也允许删去,两种表示的割值相同。布尔值虽然是 Python 整数的子类,在业务入口仍应拒绝,避免把勾选框误当成容量。

import sqlite3

def normalize(n, rows):
    result = {}
    for u, v, c in rows:
        if any(type(x) is not int for x in (u, v, c)):
            raise ValueError("integer input required")
        if not (0 <= u < n and 0 <= v < n) or u == v or c < 0:
            raise ValueError("invalid edge")
        key = tuple(sorted((u, v)))
        result[key] = result.get(key, 0) + c
    if any(c > 2**63 - 1 for c in result.values()):
        raise OverflowError("SQLite INTEGER range")
    return [(u, v, c) for (u, v), c in sorted(result.items())]

rows = normalize(5, [(1, 0, 2), (0, 1, 3), (1, 2, 0), (2, 3, 4)])
con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys=ON")
con.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY);
CREATE TABLE edge(
 u INTEGER NOT NULL REFERENCES vertex(id),
 v INTEGER NOT NULL REFERENCES vertex(id),
 c INTEGER NOT NULL CHECK(typeof(c)='integer' AND c>=0),
 PRIMARY KEY(u,v), CHECK(u<v)
);
""")
with con:
    con.executemany("INSERT INTO vertex VALUES(?)", [(i,) for i in range(5)])
    con.executemany("INSERT INTO edge VALUES(?,?,?)", rows)
print(con.execute("SELECT * FROM edge ORDER BY u,v").fetchall())
print("vertices", con.execute("SELECT COUNT(*) FROM vertex").fetchone()[0])
con.close()

运行结果:

[(0, 1, 5), (1, 2, 0), (2, 3, 4)]
vertices 5

SQLite 的 INTEGER 是有符号六十四位整数,Python 的整数则可以继续增长。即使单条容量都能入库,多条边的割容量仍可能越界,后面的证书表会把总值保存为十进制文本。数据库约束检查的是转换后的存储类型,不能替代 Python 对原始类型的校验。外键也要对每个连接显式开启。后面的求解函数假定端点有效且容量为非负 Python 整数;外部数据必须先校验。六十四位上界只约束写入 INTEGER 的数据,不限制求解器本身。

示例二:先做一个不会依赖最大流代码的真值机

对指定的不同顶点 s、t,枚举包含 s 而不包含 t 的顶点集合 S。原图每条无向边只保存一次,两个端点恰好分居两侧时才累加容量;不应因为内部用了双向残量网络而把割容量翻倍。这个穷举接口返回最小值与源点侧集合,是后续测试的独立真值机。它需要指数时间,只用于很小的图,绝不是大图加速方案。

def exact_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    best, side = None, None
    for mask in range(1 << n):
        if not (mask >> s & 1) or (mask >> t & 1):
            continue
        value = sum(c for u, v, c in edges
                    if ((mask >> u) ^ (mask >> v)) & 1)
        if best is None or value < best:
            best = value
            side = {v for v in range(n) if mask >> v & 1}
    return best, side

edges = [(0, 1, 3), (0, 2, 1), (1, 2, 2), (1, 3, 1), (2, 3, 4)]
value, side = exact_cut(4, edges, 0, 3)
print("value", value)
print("source side", sorted(side))
print("sink side", sorted(set(range(4)) - side))

运行结果:

value 4
source side [0]
sink side [1, 2, 3]

代码采用严格小于更新最优解,所以并列最小割按位掩码顺序稳定选择。切换最大流实现后,返回的集合可能不同,只要容量与最优值相等就是合法答案。测试通常应比较性质而不是强行要求同一组顶点。

示例三:核心是重接父节点,而不是保存所有两点答案

下面把最小割求解器当成可替换函数。开始时所有非根节点都指向零号根,依次选择 s 与其当前父节点 t,调用一次最小割。源点侧中仍挂在 t 下的其他节点改挂到 s;已经处理过的节点也必须纳入这次检查。其边权保持原值,尚未处理节点的临时零权重会在后续轮次被覆盖。这里采用完整的割树更新形式,不能只因为某种简写通过了数值测试,就假定它同时保持了分区证书。

def exact_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    best, side = None, None
    for mask in range(1 << n):
        if not (mask >> s & 1) or (mask >> t & 1):
            continue
        value = sum(c for u, v, c in edges
                    if ((mask >> u) ^ (mask >> v)) & 1)
        if best is None or value < best:
            best = value
            side = {v for v in range(n) if mask >> v & 1}
    return best, side

def cut_tree(n, edges, oracle, trace=None):
    if n < 1:
        raise ValueError("empty graph")
    parent, weight = [0] * n, [0] * n
    for s in range(1, n):
        t = parent[s]
        value, side = oracle(n, edges, s, t)
        # Reparent every sibling on the source side, including processed ones.
        for v in range(1, n):
            if v != s and parent[v] == t and v in side:
                parent[v] = s
        if t != 0 and parent[t] in side:
            parent[s], parent[t] = parent[t], s
            weight[s], weight[t] = weight[t], value
            if trace is not None:
                trace.append((s, t))
        else:
            weight[s] = value
    return [(v, parent[v], weight[v]) for v in range(1, n)]

edges = [(0, 1, 3), (0, 2, 1), (1, 2, 2), (1, 3, 1), (2, 3, 4)]
calls = 0
def counted(n, edges, s, t):
    global calls
    calls += 1
    return exact_cut(n, edges, s, t)
tree = cut_tree(4, edges, counted)
print("tree", tree)
print("cut calls", calls)

运行结果:

tree [(1, 0, 4), (2, 1, 4), (3, 2, 5)]
cut calls 3

树保存同一组顶点与 n−1 条加权边,建树恰好调用 n−1 次割求解器。输入若只有一个顶点,返回空边集;空图则明确报错。树边不必是原图中的边,它记录的是一对端点之间的最小割值。不要把树权解释成物理链路带宽,也不要拿它求原图最短路。

示例四:触发旋转分支,检查权重跟着哪条边走

容易写错的分支是 t 不是根,并且 t 的父节点也落在本轮源点侧。此时 s 接到 t 原来的父节点,t 改挂到 s;旧的 t 边权转交给 s,新算出的割值留给 t。若只是交换父节点却不同时转移权重,结果仍可能长得像一棵树,却不再表示正确的割。下面用三点链故意触发这个分支,而不是期待随机测试碰巧覆盖它。

def exact_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    best, side = None, None
    for mask in range(1 << n):
        if not (mask >> s & 1) or (mask >> t & 1):
            continue
        value = sum(c for u, v, c in edges
                    if ((mask >> u) ^ (mask >> v)) & 1)
        if best is None or value < best:
            best = value
            side = {v for v in range(n) if mask >> v & 1}
    return best, side

def cut_tree(n, edges, oracle, trace=None):
    if n < 1:
        raise ValueError("empty graph")
    parent, weight = [0] * n, [0] * n
    for s in range(1, n):
        t = parent[s]
        value, side = oracle(n, edges, s, t)
        # Reparent every sibling on the source side, including processed ones.
        for v in range(1, n):
            if v != s and parent[v] == t and v in side:
                parent[v] = s
        if t != 0 and parent[t] in side:
            parent[s], parent[t] = parent[t], s
            weight[s], weight[t] = weight[t], value
            if trace is not None:
                trace.append((s, t))
        else:
            weight[s] = value
    return [(v, parent[v], weight[v]) for v in range(1, n)]

edges = [(0, 2, 1), (1, 2, 2)]
trace = []
print("tree", cut_tree(3, edges, exact_cut, trace))
print("rotations", trace)

运行结果:

tree [(1, 2, 2), (2, 0, 1)]
rotations [(2, 1)]

本例第一次把两个非根节点暂时组织在一起,第二次发现新的割跨过旧父边,于是发生旋转。父节点数组是算法维护的结构,不是按编号大小定义的层级;不要增加父节点编号必须更小的错误约束。

示例五:从 SQLite 读树,返回数值与原图割证书

两点查询只需沿树上的唯一通路找最小边权。这里同时返回瓶颈边的行号,方便删除该树边后找出包含 s 的连通分量。一个可核验的证书至少应包含图版本、查询端点、两侧顶点与跨割原边;复核器重新检查两侧覆盖全部顶点且不相交、s 与 t 分居两侧,并独立累加原图容量。并列瓶颈使用行号作稳定决胜,不影响割树的正确性。

import sqlite3

def component(n, tree, removed, start):
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        if i != removed:
            adj[u].append(v)
            adj[v].append(u)
    seen, stack = {start}, [start]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

def capacity(edges, side):
    return sum(c for u, v, c in edges if (u in side) != (v in side))

def query(n, tree, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        adj[u].append((v, w, i))
        adj[v].append((u, w, i))
    stack, seen = [(s, None)], {s}
    while stack:
        u, best = stack.pop()
        if u == t:
            return best
        for v, w, i in adj[u]:
            if v not in seen:
                seen.add(v)
                candidate = (w, i)
                stack.append((v, candidate if best is None else min(best, candidate)))
    raise ValueError("not a connected tree")

edges = [(0, 1, 3), (0, 2, 1), (1, 2, 2), (1, 3, 1), (2, 3, 4)]
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE tree(child INTEGER PRIMARY KEY, parent INTEGER, value INTEGER)")
con.executemany("INSERT INTO tree VALUES(?,?,?)", [(1, 0, 4), (2, 1, 4), (3, 2, 5)])
tree = con.execute("SELECT * FROM tree ORDER BY child").fetchall()
value, edge_id = query(4, tree, 0, 3)
side = component(4, tree, edge_id, 0)
other = set(range(4)) - side
crossing = [(u, v, c) for u, v, c in edges if (u in side) != (v in side)]
assert 0 in side and 3 in other and capacity(edges, side) == value
print("value", value)
print("partition", sorted(side), sorted(other))
print("crossing", crossing)
con.close()

运行结果:

value 4
partition [0] [1, 2, 3]
crossing [(0, 1, 3), (0, 2, 1)]

本例的树是示例三算出的固定夹具,因此可以单独复制运行。这里的小容量树权使用 INTEGER;通用系统的树权同样需要保存为十进制文本,或在入库前检查六十四位上界。一般查询的线性实现耗时与顶点数成正比;查询特别多时,可预处理树的倍增祖先与路径最小值,把只求数值的查询降到对数时间。完整输出分区及原边仍有输出规模成本,不能宣称也必然是对数时间。

示例六:数值全对,也可能给出错误的分区

必须区分等价流值树与真正的割树。以下原图是容量全为一的四边环,任意两个不同顶点的最小割值都是二。我们人为构造另一棵每条边都标二的路径树,因此它也能答对全部两点数值;但删除中间边得到交错分区,原图跨越该分区的四条边总容量是四。这就是仅做数值回归测试的盲点。

from itertools import combinations

def exact_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    best, side = None, None
    for mask in range(1 << n):
        if not (mask >> s & 1) or (mask >> t & 1):
            continue
        value = sum(c for u, v, c in edges
                    if ((mask >> u) ^ (mask >> v)) & 1)
        if best is None or value < best:
            best = value
            side = {v for v in range(n) if mask >> v & 1}
    return best, side

def component(n, tree, removed, start):
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        if i != removed:
            adj[u].append(v)
            adj[v].append(u)
    seen, stack = {start}, [start]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

def capacity(edges, side):
    return sum(c for u, v, c in edges if (u in side) != (v in side))

def query(n, tree, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        adj[u].append((v, w, i))
        adj[v].append((u, w, i))
    stack, seen = [(s, None)], {s}
    while stack:
        u, best = stack.pop()
        if u == t:
            return best
        for v, w, i in adj[u]:
            if v not in seen:
                seen.add(v)
                candidate = (w, i)
                stack.append((v, candidate if best is None else min(best, candidate)))
    raise ValueError("not a connected tree")

edges = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (0, 3, 1)]
fake_tree = [(0, 2, 2), (2, 1, 2), (1, 3, 2)]
values_ok = all(query(4, fake_tree, s, t)[0] == exact_cut(4, edges, s, t)[0]
                for s, t in combinations(range(4), 2))
side = component(4, fake_tree, 1, 0)
print("all pair values correct", values_ok)
print("partition", sorted(side), sorted(set(range(4)) - side))
print("claimed", 2, "actual", capacity(edges, side))

运行结果:

all pair values correct True
partition [0, 2] [1, 3]
claimed 2 actual 4

证书的跨割容量等于一个未经验证的树值,只说明两份数据彼此一致,还不能单独证明最优。最优性还需要可信建树过程、独立最小割求解器,或容量相等的可行流作为下界。本教程对小图采用完全枚举建立最优下界,最后同时检查每条树边诱导的分区。

示例七:把教学真值机换成整数残量网络

真实工作流不应枚举所有子集。下面提供一个短小的广度优先增广接口,让本节脱离前面的代码也能运行。每次调用重新建立残量矩阵,避免前一对端点的流状态污染下一次查询;无向容量在两个方向初始化,更新时允许反向撤销。没有增广路时,可达集合就是源点侧。核心重点仍是割树,不在这里重复展开最大流的完整推导。

from collections import deque

def flow_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    residual = [[0] * n for _ in range(n)]
    for u, v, c in edges:
        residual[u][v] += c
        residual[v][u] += c
    total = 0
    while True:
        prev = [-1] * n
        prev[s] = s
        queue = deque([s])
        while queue and prev[t] == -1:
            u = queue.popleft()
            for v in range(n):
                if prev[v] == -1 and residual[u][v] > 0:
                    prev[v] = u
                    queue.append(v)
        if prev[t] == -1:
            return total, {v for v in range(n) if prev[v] != -1}
        v, amount = t, None
        while v != s:
            u = prev[v]
            amount = residual[u][v] if amount is None else min(amount, residual[u][v])
            v = u
        v = t
        while v != s:
            u = prev[v]
            residual[u][v] -= amount
            residual[v][u] += amount
            v = u
        total += amount

def cut_tree(n, edges, oracle, trace=None):
    if n < 1:
        raise ValueError("empty graph")
    parent, weight = [0] * n, [0] * n
    for s in range(1, n):
        t = parent[s]
        value, side = oracle(n, edges, s, t)
        # Reparent every sibling on the source side, including processed ones.
        for v in range(1, n):
            if v != s and parent[v] == t and v in side:
                parent[v] = s
        if t != 0 and parent[t] in side:
            parent[s], parent[t] = parent[t], s
            weight[s], weight[t] = weight[t], value
            if trace is not None:
                trace.append((s, t))
        else:
            weight[s] = value
    return [(v, parent[v], weight[v]) for v in range(1, n)]

def component(n, tree, removed, start):
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        if i != removed:
            adj[u].append(v)
            adj[v].append(u)
    seen, stack = {start}, [start]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

def capacity(edges, side):
    return sum(c for u, v, c in edges if (u in side) != (v in side))

edges = [(0, 1, 3), (0, 2, 1), (1, 2, 2), (1, 3, 1), (2, 3, 4)]
tree = cut_tree(4, edges, flow_cut)
print("tree", tree)
print("certified edges", sum(capacity(edges, component(4, tree, i, u)) == w
                               for i, (u, v, w) in enumerate(tree)))

运行结果:

tree [(1, 0, 4), (2, 1, 4), (3, 2, 5)]
certified edges 3

本实现是便于审阅的稠密矩阵版,不应直接套用邻接表版的复杂度结论。矩阵占用二次空间,每次搜索扫描整行;容量采用任意精度整数,不依赖浮点容差,也没有用有限的大常数假装无穷。零容量图与不连通图会自然产生零割值,割树仍可用零权边连接各部分。

示例八:事务保存证书,并拒绝过期快照

数据库层最重要的不是缓存一个数字,而是锁定它对应哪份原图。下面用规范化的顶点数与边列表计算摘要,证书与该摘要在同一条记录中提交;总割值以十进制文本保存,读取后交回 Python 整数计算。生产环境还应保存建树版本、原始边快照与校验状态。摘要只能识别内容是否变化,并不能证明内容本身正确;输入读取若跨多张表,应放在同一个读事务中取得一致快照。

import hashlib
import json
import sqlite3

def fingerprint(n, edges):
    raw = json.dumps([n, sorted(edges)], separators=(",", ":"))
    return hashlib.sha256(raw.encode()).hexdigest()

edges = [(0, 1, 3), (0, 2, 1), (1, 2, 2), (1, 3, 1), (2, 3, 4)]
side = [0]
value = sum(c for u, v, c in edges if (u in side) != (v in side))
con = sqlite3.connect(":memory:")
con.execute("""CREATE TABLE certificate(
 graph_hash TEXT NOT NULL, s INTEGER, t INTEGER,
 value_text TEXT NOT NULL, source_side TEXT NOT NULL,
 PRIMARY KEY(graph_hash,s,t))""")
snapshot = fingerprint(4, edges)
with con:
    con.execute("INSERT INTO certificate VALUES(?,?,?,?,?)",
                (snapshot, 0, 3, str(value), json.dumps(side)))
row = con.execute("SELECT graph_hash,value_text,source_side FROM certificate").fetchone()
assert row[0] == fingerprint(4, edges)
print("restored", int(row[1]), json.loads(row[2]))
try:
    with con:
        con.execute("INSERT INTO certificate VALUES(?,?,?,?,?)",
                    (snapshot, 0, 3, "999", "[]"))
except sqlite3.IntegrityError:
    print("duplicate rolled back")
changed = [(0, 1, 4)] + edges[1:]
print("stale", row[0] != fingerprint(4, changed))
print("rows", con.execute("SELECT COUNT(*) FROM certificate").fetchone()[0])
con.close()

运行结果:

restored 4 [0]
duplicate rolled back
stale True
rows 1

图更新后,旧树和旧证书可能都失效。最稳妥的起点是按完整快照重建,而不是擅自只修改一条树边。零权值也不能被当成没有缓存的标记,应使用缺失行或单独状态。SQLite 连接的上下文管理器处理事务提交和回滚,但不会替你关闭连接,所以示例仍显式调用关闭操作。

示例九:穷举所有四点小图,同时核验数值和分区

最后给出能够独立运行的完整回归脚本。四个顶点共有六条可能边,每条容量取零、一、二,总计三的六次方,即七百二十九张图。每张图检查全部六个点对,再检查三条树边的基本割:它既要切开树边端点,容量也要等于该端点对的精确最小割。此测试自然包括空边集、不连通、零容量、并列割与多种旋转情况。额外加入单点图、空图拒绝及超过 SQLite 整数上界的大容量图,避免只在常规路径上得到漂亮结果。

from itertools import combinations, product

def exact_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    best, side = None, None
    for mask in range(1 << n):
        if not (mask >> s & 1) or (mask >> t & 1):
            continue
        value = sum(c for u, v, c in edges
                    if ((mask >> u) ^ (mask >> v)) & 1)
        if best is None or value < best:
            best = value
            side = {v for v in range(n) if mask >> v & 1}
    return best, side

from collections import deque

def flow_cut(n, edges, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    residual = [[0] * n for _ in range(n)]
    for u, v, c in edges:
        residual[u][v] += c
        residual[v][u] += c
    total = 0
    while True:
        prev = [-1] * n
        prev[s] = s
        queue = deque([s])
        while queue and prev[t] == -1:
            u = queue.popleft()
            for v in range(n):
                if prev[v] == -1 and residual[u][v] > 0:
                    prev[v] = u
                    queue.append(v)
        if prev[t] == -1:
            return total, {v for v in range(n) if prev[v] != -1}
        v, amount = t, None
        while v != s:
            u = prev[v]
            amount = residual[u][v] if amount is None else min(amount, residual[u][v])
            v = u
        v = t
        while v != s:
            u = prev[v]
            residual[u][v] -= amount
            residual[v][u] += amount
            v = u
        total += amount

def cut_tree(n, edges, oracle, trace=None):
    if n < 1:
        raise ValueError("empty graph")
    parent, weight = [0] * n, [0] * n
    for s in range(1, n):
        t = parent[s]
        value, side = oracle(n, edges, s, t)
        # Reparent every sibling on the source side, including processed ones.
        for v in range(1, n):
            if v != s and parent[v] == t and v in side:
                parent[v] = s
        if t != 0 and parent[t] in side:
            parent[s], parent[t] = parent[t], s
            weight[s], weight[t] = weight[t], value
            if trace is not None:
                trace.append((s, t))
        else:
            weight[s] = value
    return [(v, parent[v], weight[v]) for v in range(1, n)]

def component(n, tree, removed, start):
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        if i != removed:
            adj[u].append(v)
            adj[v].append(u)
    seen, stack = {start}, [start]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return seen

def capacity(edges, side):
    return sum(c for u, v, c in edges if (u in side) != (v in side))

def query(n, tree, s, t):
    if s == t or not (0 <= s < n and 0 <= t < n):
        raise ValueError("different valid terminals required")
    adj = [[] for _ in range(n)]
    for i, (u, v, w) in enumerate(tree):
        adj[u].append((v, w, i))
        adj[v].append((u, w, i))
    stack, seen = [(s, None)], {s}
    while stack:
        u, best = stack.pop()
        if u == t:
            return best
        for v, w, i in adj[u]:
            if v not in seen:
                seen.add(v)
                candidate = (w, i)
                stack.append((v, candidate if best is None else min(best, candidate)))
    raise ValueError("not a connected tree")

pairs = list(combinations(range(4), 2))
graphs = pair_checks = certificates = 0
for weights in product(range(3), repeat=len(pairs)):
    edges = [(u, v, c) for (u, v), c in zip(pairs, weights)]
    tree = cut_tree(4, edges, flow_cut)
    assert len(tree) == 3
    for s, t in pairs:
        assert query(4, tree, s, t)[0] == exact_cut(4, edges, s, t)[0]
        pair_checks += 1
    for i, (u, v, w) in enumerate(tree):
        side = component(4, tree, i, u)
        assert u in side and v not in side
        assert capacity(edges, side) == w == exact_cut(4, edges, u, v)[0]
        certificates += 1
    graphs += 1
assert cut_tree(1, [], flow_cut) == []
empty_tree = cut_tree(4, [], flow_cut)
assert query(4, empty_tree, 0, 3)[0] == 0
try:
    query(4, empty_tree, 0, 0)
except ValueError:
    pass
else:
    raise AssertionError("self query accepted")
try:
    cut_tree(0, [], flow_cut)
except ValueError:
    pass
else:
    raise AssertionError("empty graph accepted")
big = 2**63 + 7
assert cut_tree(2, [(0, 1, big)], flow_cut) == [(1, 0, big)]
print("graphs", graphs)
print("pair checks", pair_checks)
print("cut certificates", certificates)
print("boundary tests passed")

运行结果:

graphs 729
pair checks 4374
cut certificates 2187
boundary tests passed

这些断言不是一般情形的数学证明,但能针对实现错误提供比单个示意图强得多的证据。继续扩展测试时,可改变顶点顺序、合并或拆分平行边、加入孤立点,再比较同一性质;固定随机种子能补充较大样本,不能取代上述可复现的穷举集合。上线前还应对数据库读取后的树结构检查顶点集合、无环、连通和边数,并在摘要不一致时拒绝服务旧结果。

落地时的取舍

如果只有一个点对,先直接计算最小割更简单;如果原图长期稳定、两点查询很多,再考虑用割树摊薄建树成本。把一次割求解的成本记作 F,父节点维护额外需要二次规模的检查,整体可写为 n−1 次割求解加这部分维护开销。更快的求解器、稀疏表示和查询索引应分别优化,不能把树压缩后的存储优势误说成建树几乎免费。

推荐保存原图规范快照、割树边、版本摘要和校验结果四类数据。用户需要解释时再输出一侧顶点与跨割原边;需要严格独立的最优性证明时再补充流证书或使用独立求解器。先让数值、分区与版本三者能够相互核对,再追求更快的批量查询。

参考资料与核验范围

资料核验日期:2026年10月20日。示例中的输出由独立脚本实际执行生成;所有测试图均为教学构造,不代表真实业务容量。

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