Python+SQLite 精确求解无向中国邮差问题:奇点配对、边副本与路线回放

10-20 4阅读

巡视园区道路、检查管线或安排扫街车辆时,任务常常是把每条路至少走一次,最后回到出发点。这里的成本来自实际走过的边,而不是访问过多少个地点。本文把这个目标落成一个可以运行、可以入库、可以逐步回放的无向中国邮差问题求解器。输入是连通的无向多重图,每条原始边都有独立编号,权重是非负整数;输出是一条覆盖所有原始边的最短闭合路线。

本文假设读者已了解最短路和欧拉遍历,不再分别重讲这些基础算法。真正需要补齐的是它们之间的接口:为什么只需处理奇度顶点,为什么必须全局配对,最短路展开后怎样保留平行边身份,以及怎样证明数据库里保存的路线仍然对应当时那张图。最小生成树只要求连通,不能删除本题中必须服务的原始边,因此不能替代这里的优化目标。

Python+SQLite 精确求解无向中国邮差问题:奇点配对、边副本与路线回放
AI概念图:覆盖道路并允许重复经过的巡检路线。画面只表达主题,节点、箭头和路段不对应下文测试数据,也不作为算法正确性的证据。

先说清楚问题边界和最优性

我们的路线必须闭合;出发点可以指定,但不能要求终点另在一个位置。所有边均可双向行走,所有原始边都必须覆盖,平行边是不同任务,自环也是一条任务。单个顶点且没有边时,停在原地就是成本为零的合法答案;两个以上顶点存在孤立点时,本实现直接拒绝。负权、方向限制、转弯惩罚、服务时间窗和只覆盖部分边都属于别的模型,不能通过调几个参数假装已经支持。

记全部原始边的权重之和为 B,奇度顶点集合为 T。任何闭合路线都至少支付 B;把每条原始边首次出现以外的行走抽出来,就得到额外边的多重集合。闭合路线在每个顶点的总度数为偶数,所以这个额外集合的奇度顶点恰好是 T。把它分解成连接奇度顶点的路径与若干环,可以得到一组 T 的完美配对。非负权保证删除这些额外环不会增加成本,再把每条连接路径替换成对应最短路也不会变贵。因此,任何合法路线的额外成本都不低于奇点最短距离完全图上的最小权完美配对值 M。

反过来,取这组最小配对,并在原图中复制每对顶点之间的一条最短路径。路径内部顶点每次增加两个关联端,端点增加一个;每个奇点恰好成为一次端点,因此所有顶点都变成偶度。原图本来连通,添加副本不会破坏连通性,增广图就存在欧拉回路。遍历这些边实例的成本恰为 B+M,同时达到前面的下界,所以得到全局最优解。这段上下界论证解释了组合方式;经典匹配理论背景可参考 Edmonds 与 Johnson 的原始论文 Matching, Euler tours and the Chinese postman。

实现采用位掩码动态规划,明确限制奇点数量 k 不超过 16。这个限制是教学实现的资源护栏,不是中国邮差问题的理论复杂度结论。无向版本可借助更通用的最小权完美匹配算法处理更大的奇点集合;本文不实现 blossom,也不会在超限时偷偷切换成贪心并继续声称最优。下面九段 Python 代码都可单独复制运行,使用 Python 3.10 或更新版本的标准库,无须先执行上一段;每段后面给出完整标准输出。

示例一:SQLite 保存的是边,不是顶点对

贯穿全文的小图只有 A、B、C、D 四个顶点,却故意含有三条 A—B 平行边和一个零成本自环。表的主键必须是 edge_id,不能把端点对设为唯一键,否则三条路会被合并。即使两条边端点和成本都相同,也仍然可能代表不同的巡检对象。SQLite 的 CREATE TABLE 文档说明了主键、非空与检查约束的语义;这里用它们表达存储层能负责的局部条件。

统计度数时使用 UNION ALL,让每条边的两个端点分别贡献一次计数,自环也就自然贡献二。不要改成 UNION 去重。这个查询只列出有边关联的顶点;完整的孤立点检查交给下一节。所有数据库连接都在事务开始前显式开启外键,并用参数占位符传值,避免把标签拼到 SQL 文本里。外键开关是逐连接的,不能依赖上一次连接的状态,详见 SQLite 外键文档。

import sqlite3

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    edge_id INTEGER PRIMARY KEY CHECK(edge_id > 0),
    u TEXT NOT NULL REFERENCES vertex(name),
    v TEXT NOT NULL REFERENCES vertex(name),
    weight INTEGER NOT NULL
        CHECK(typeof(weight) = 'integer' AND weight >= 0)
);
""")
with con:
    con.executemany("INSERT INTO vertex VALUES(?)",
                    [(v,) for v in VERTICES])
    con.executemany("INSERT INTO edge VALUES(?,?,?,?)", EDGES)
print("edges =", con.execute("SELECT COUNT(*) FROM edge").fetchone()[0])
print("A-B IDs =", [
    row[0] for row in con.execute(
        "SELECT edge_id FROM edge WHERE u=? AND v=? ORDER BY edge_id",
        ("A", "B"),
    )
])
degrees = con.execute("""
    SELECT name, COUNT(*) AS degree
    FROM (
        SELECT u AS name FROM edge
        UNION ALL
        SELECT v AS name FROM edge
    )
    GROUP BY name ORDER BY name
""").fetchall()
print("degrees =", degrees)
print("odd =", [v for v, d in degrees if d % 2])
con.close()

完整输出:

edges = 9
A-B IDs = [1, 7, 8]
degrees = [('A', 5), ('B', 5), ('C', 5), ('D', 3)]
odd = ['A', 'B', 'C', 'D']

成本为 7 的 A—B 边也必须至少走一次;最短路后来选用成本为 1 的那条,只决定补走哪条路。把这个区别混淆,往往会得到一个看似便宜却漏检原始任务的答案。

示例二:先验证模型,再谈精确求解

输入校验同时保护数学假设和数据库边界。权重与编号采用 Python 的严格整数类型检查,因而布尔值不会被当成 0 或 1 悄悄接受。边权、编号限制在 SQLite 有符号 64 位整数范围内,但路线总成本在 Python 中累加,可以超过这一范围。顶点用非空字符串,允许任意 Unicode 标签;为了使演示输出可重复,顶点、原始边和邻接项都会排序。

连通性检查覆盖全部声明顶点,而不是只检查出现过边的顶点。对于真正分离的路网,不存在单条覆盖所有边的闭合步行。业务若允许车辆装载转运,应把这种移动成本建成真实可走的连接边,或改用其他模型,而不是在不可达点之间插入一条成本为零的虚构连接。以下函数还将零权自环保留下来,并准确计算它的度数贡献。

LIMIT = 16
MAX_INT = 2**63 - 1

def prepare(vertices, edges):
    vertices = list(vertices)
    if not vertices or any(type(v) is not str or not v for v in vertices):
        raise ValueError("vertices must be nonempty strings")
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    vertices.sort()
    adj = {v: [] for v in vertices}
    degree = dict.fromkeys(vertices, 0)
    seen = set()
    clean = []
    for eid, u, v, w in edges:
        if type(eid) is not int or not 1 <= eid <= MAX_INT or eid in seen:
            raise ValueError("invalid or duplicate edge ID")
        if u not in adj or v not in adj:
            raise ValueError("unknown endpoint")
        if type(w) is not int or not 0 <= w <= MAX_INT:
            raise ValueError("weight must be a nonnegative 64-bit integer")
        seen.add(eid)
        clean.append((eid, u, v, w))
        adj[u].append((v, w, eid))
        adj[v].append((u, w, eid))
        degree[u] += 1
        degree[v] += 1
    for values in adj.values():
        values.sort()
    visited = {vertices[0]}
    stack = [vertices[0]]
    while stack:
        for v, _, _ in adj[stack.pop()]:
            if v not in visited:
                visited.add(v)
                stack.append(v)
    if len(visited) != len(vertices):
        raise ValueError("graph is disconnected")
    return vertices, sorted(clean), adj, degree

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

_, _, _, degree = prepare(VERTICES, EDGES)
print("valid degrees =", sorted(degree.items()))
print("single =", prepare(["A"], [])[3])
cases = [
    ("disconnected", ["A", "B"], []),
    ("negative", ["A"], [(1, "A", "A", -1)]),
    ("boolean", ["A"], [(1, "A", "A", True)]),
    ("duplicate ID", ["A"], [(1, "A", "A", 0), (1, "A", "A", 2)]),
]
for label, vertices, edges in cases:
    try:
        prepare(vertices, edges)
    except ValueError as error:
        print(label + ":", error)

完整输出:

valid degrees = [('A', 5), ('B', 5), ('C', 5), ('D', 3)]
single = {'A': 0}
disconnected: graph is disconnected
negative: weight must be a nonnegative 64-bit integer
boolean: weight must be a nonnegative 64-bit integer
duplicate ID: invalid or duplicate edge ID

数据库的类型亲和性可能将某些输入转换后再保存,所以严格拒绝布尔值等 API 输入的职责仍在 Python 层。读取历史数据库时也要重新验证,不能把一张存在的表直接当成已满足算法前提的图。

示例三:奇点距离之外,还要记录原始边编号

接下来只从奇度顶点出发计算最短路。配对算法需要距离矩阵,而复制阶段需要能回到原图的路径,因此 parent 记录前驱顶点和原始边编号两项。若只保存前驱顶点,在平行边之间便无法判断究竟复制了哪条路。这里沿用非负权最短路的堆实现,堆元素是距离和字符串标签;Python 官方 heapq 文档给出了最小堆与元组比较的基础约定。

松弛条件必须是严格小于,而不是小于等于。零权边形成等长候选时,反复改写前驱不仅无益,还可能使路径恢复变得危险。我们保留首次确定的等长选择,并靠排序让该选择稳定。这并不保证输出是所有最短路径中字典序最小的一条,也不需要这种保证;任何一条成本相同的合法最短路都能支撑最优邮差路线。

from heapq import heappop, heappush

LIMIT = 16
MAX_INT = 2**63 - 1

def prepare(vertices, edges):
    vertices = list(vertices)
    if not vertices or any(type(v) is not str or not v for v in vertices):
        raise ValueError("vertices must be nonempty strings")
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    vertices.sort()
    adj = {v: [] for v in vertices}
    degree = dict.fromkeys(vertices, 0)
    seen = set()
    clean = []
    for eid, u, v, w in edges:
        if type(eid) is not int or not 1 <= eid <= MAX_INT or eid in seen:
            raise ValueError("invalid or duplicate edge ID")
        if u not in adj or v not in adj:
            raise ValueError("unknown endpoint")
        if type(w) is not int or not 0 <= w <= MAX_INT:
            raise ValueError("weight must be a nonnegative 64-bit integer")
        seen.add(eid)
        clean.append((eid, u, v, w))
        adj[u].append((v, w, eid))
        adj[v].append((u, w, eid))
        degree[u] += 1
        degree[v] += 1
    for values in adj.values():
        values.sort()
    visited = {vertices[0]}
    stack = [vertices[0]]
    while stack:
        for v, _, _ in adj[stack.pop()]:
            if v not in visited:
                visited.add(v)
                stack.append(v)
    if len(visited) != len(vertices):
        raise ValueError("graph is disconnected")
    return vertices, sorted(clean), adj, degree

def shortest(adj, source):
    dist, parent = {source: 0}, {}
    heap = [(0, source)]
    while heap:
        cost, u = heappop(heap)
        if cost != dist[u]:
            continue
        for v, w, eid in adj[u]:
            candidate = cost + w
            if v not in dist or candidate < dist[v]:
                dist[v] = candidate
                parent[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, parent

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

vertices, _, adj, degree = prepare(VERTICES, EDGES)
odd = [v for v in vertices if degree[v] % 2]
for u in odd:
    dist, _ = shortest(adj, u)
    print(u, [dist[v] for v in odd])
distance, parent = shortest(adj, "A")
cursor, path = "C", []
while cursor != "A":
    cursor, eid = parent[cursor]
    path.append(eid)
print("A-C =", distance["C"], list(reversed(path)))

完整输出:

A [0, 1, 3, 2]
B [1, 0, 2, 3]
C [3, 2, 0, 2]
D [2, 3, 2, 0]
A-C = 3 [8, 2]

A 到 C 的直接边成本为 5,但补走时采用编号 8 和 2,总成本为 3。原始编号 5 并没有因此消失:它仍在 B 中,也仍必须出现在最后的覆盖路线里。

示例四:固定最低位,穷尽所有配对可能

把奇点按排序编号为 0 到 k−1,mask 的置位表示还没有配对的顶点。每个状态固定最小的未配对下标 i,再尝试所有其他未配对下标 j,转移到同时删去 i、j 的状态。这样既不会遗漏任何完美配对,也避免了把同一组配对仅因选取顺序不同而重复展开。空集合的最优成本是零,这也自然覆盖了原图已经具有欧拉回路的情况。

记忆化状态只存成本,恢复时再次扫描候选,找到与最优值相等的第一项。我们使用整数精确比较,无须给浮点误差设容忍带。矩阵来自已验证连通图的最短路,因此这里的内部函数不再重复校验对称性和三角不等式。若把它单独公开为 API,应另加矩阵维度和数值类型检查。

from functools import lru_cache

LIMIT = 16
MAX_INT = 2**63 - 1

def pairing(distance):
    k = len(distance)
    if k % 2 or k > LIMIT:
        raise ValueError("odd vertex count must be even and <= 16")

    @lru_cache(None)
    def dp(mask):
        if not mask:
            return 0
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        return min(
            distance[i][j] + dp(rest ^ (1 << j))
            for j in range(i + 1, k) if rest & (1 << j)
        )

    mask, pairs = (1 << k) - 1, []
    optimum = dp(mask)
    while mask:
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        for j in range(i + 1, k):
            if rest & (1 << j) and (
                distance[i][j] + dp(rest ^ (1 << j)) == dp(mask)
            ):
                pairs.append((i, j))
                mask = rest ^ (1 << j)
                break
    return optimum, pairs

names = list("ABCD")
distance = [
    [0, 1, 3, 2], [1, 0, 2, 3],
    [3, 2, 0, 2], [2, 3, 2, 0],
]
all_pairings = [
    [(0, 1), (2, 3)],
    [(0, 2), (1, 3)],
    [(0, 3), (1, 2)],
]
print("candidate costs =", [
    sum(distance[i][j] for i, j in pairs) for pairs in all_pairings
])
cost, pairs = pairing(distance)
print("minimum =", cost)
print("pairs =", [(names[i], names[j]) for i, j in pairs])
print("already Eulerian =", pairing([]))

完整输出:

candidate costs = [3, 6, 4]
minimum = 3
pairs = [('A', 'B'), ('C', 'D')]
already Eulerian = (0, [])

四个奇点共有三种完美配对,代价分别为 3、6、4,最优值是 3。就近先配一个奇点并不是一般正确的证明;局部便宜的选择可能把剩下两点留成昂贵的一对。位掩码动态规划的价值正是明确地比较完整组合。

示例五:新增实例,保持原始边身份不变

复制路径不是在原始 edge 表里修改一条边的权重,也不是给同一行打一个已访问标记。我们建立独立的边实例序列,每个实例都有 instance_id,同时保留 original_edge_id。原始边先各产生一个实例,所选最短路上的每一次复制再追加一个实例。实例可以被欧拉遍历恰好消费一次,原始边则可能在路线中出现多次。

编号 8 的原始边和新增实例 10 指向同一条道路;编号 3 的新增实例是 11。这个两层身份约定让审计能够分别回答两个问题:任务是否全部覆盖,以及每次实际行走是否只被记账一次。多条配对路径若共同经过某条边,必须保留它们各自的副本,不能用集合把重复编号消掉。

from collections import Counter

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

selected_paths = [[8], [3]]
by_id = {eid: (u, v, w) for eid, u, v, w in EDGES}
instances = [
    (iid, eid, u, v, w)
    for iid, (eid, u, v, w) in enumerate(EDGES, 1)
]
for path in selected_paths:
    for eid in path:
        instances.append((len(instances) + 1, eid, *by_id[eid]))
degree = Counter()
for _, _, u, v, _ in instances:
    degree[u] += 1
    degree[v] += 1
multiplicity = Counter(eid for _, eid, _, _, _ in instances)
print("new instances =", instances[len(EDGES):])
print("degrees =", sorted(degree.items()))
print("repeated originals =", sorted(
    (eid, count) for eid, count in multiplicity.items() if count > 1
))
print("extra =", sum(w for _, _, _, _, w in instances[len(EDGES):]))

完整输出:

new instances = [(10, 8, 'A', 'B', 1), (11, 3, 'C', 'D', 2)]
degrees = [('A', 6), ('B', 6), ('C', 6), ('D', 4)]
repeated originals = [(3, 2), (8, 2)]
extra = 3

增广后度数全部为偶数,但这只是一条结构检查,还不是完整路线证书。下一阶段必须真的给出连续、闭合、逐实例覆盖的行走顺序,最后还要对照原图复算费用。

示例六:欧拉遍历只消耗实例编号

此处不重新展开欧拉算法的原理,重点看接口。邻接表里放的是实例编号与另一端,used 也按实例编号去重。无向边在两个端点的邻接表各出现一次,自环则在同一个邻接表出现两次;两者都只能让同一个实例被消费一次。迭代式栈避免路线较长时触碰 Python 递归深度。

输出的每步有六个字段:顺序号、实例编号、原始边编号、起点、终点、权重。回溯得到的是逆序,所以最终要反转。因为代码总是取当前最小实例编号,固定图快照会得到固定的路线;这个确定性只是便于测试和比较,不能理解成邮差最优路线本身唯一。该函数是内部构件,调用方负责保证实例来自前面的连通偶度增广图。

def euler(vertices, instances, start):
    # instances: (instance_id, original_edge_id, u, v, weight)
    adj = {v: [] for v in vertices}
    lookup = {}
    for iid, eid, u, v, w in instances:
        lookup[iid] = (eid, w)
        adj[u].append((iid, v))
        adj[v].append((iid, u))
    for values in adj.values():
        values.sort(reverse=True)
    used, stack, reverse = set(), [(start, None)], []
    while stack:
        u = stack[-1][0]
        while adj[u] and adj[u][-1][0] in used:
            adj[u].pop()
        if adj[u]:
            iid, v = adj[u].pop()
            used.add(iid)
            stack.append((v, (iid, u, v)))
        else:
            _, incoming = stack.pop()
            if incoming is not None:
                reverse.append(incoming)
    if len(used) != len(instances):
        raise ValueError("unused edge instance")
    steps = []
    for seq, (iid, u, v) in enumerate(reversed(reverse)):
        eid, w = lookup[iid]
        steps.append((seq, iid, eid, u, v, w))
    return steps

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

instances = [
    (iid, eid, u, v, w)
    for iid, (eid, u, v, w) in enumerate(EDGES, 1)
] + [(10, 8, "A", "B", 1), (11, 3, "C", "D", 2)]
steps = euler(VERTICES, instances, "A")
print("original IDs =", [step[2] for step in steps])
print("instance IDs =", [step[1] for step in steps])
print("walk =", "A" + "".join("->" + step[4] for step in steps))
print("total =", sum(step[5] for step in steps))

完整输出:

original IDs = [1, 2, 3, 4, 5, 9, 3, 6, 7, 8, 8]
instance IDs = [1, 2, 3, 4, 5, 9, 11, 6, 7, 8, 10]
walk = A->B->C->D->A->C->C->D->B->A->B->A
total = 29

最终原始编号序列出现两次 8:它的原始实例加一个补走实例。与它同端点的编号 1、7 各自出现一次。应以编号和次数核对覆盖,不能只看 A—B 这一段文字是否重复。

示例七:整合求解器与可行性回放器

下面是一段完整、独立的求解程序,包含前述构件以及 replay。保留重复定义是为了让读者无需拼接前文就能直接运行。solve 返回奇点、配对、被复制的路径、边实例和最终步骤;replay 则只根据原图与步骤重新检查端点、方向、序号、实例唯一性、费用、闭合性和原始边覆盖。

必须分清可行性与最优性:回放成功证明这份记录是一条成本正确的覆盖闭合路线,不能仅凭此证明它最短。最优性来自已证明的 B+M 构造以及精确计算 M 的程序。审计不信任求解进程时,可以从同一个快照重算奇点距离与最小配对值,再比较回放成本;后面的穷举测试进一步用另一种状态空间模型交叉验证实现。

from functools import lru_cache
from heapq import heappop, heappush

LIMIT = 16
MAX_INT = 2**63 - 1


def prepare(vertices, edges):
    vertices = list(vertices)
    if not vertices or any(type(v) is not str or not v for v in vertices):
        raise ValueError("vertices must be nonempty strings")
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    vertices.sort()
    adj = {v: [] for v in vertices}
    degree = dict.fromkeys(vertices, 0)
    seen = set()
    clean = []
    for eid, u, v, w in edges:
        if type(eid) is not int or not 1 <= eid <= MAX_INT or eid in seen:
            raise ValueError("invalid or duplicate edge ID")
        if u not in adj or v not in adj:
            raise ValueError("unknown endpoint")
        if type(w) is not int or not 0 <= w <= MAX_INT:
            raise ValueError("weight must be a nonnegative 64-bit integer")
        seen.add(eid)
        clean.append((eid, u, v, w))
        adj[u].append((v, w, eid))
        adj[v].append((u, w, eid))
        degree[u] += 1
        degree[v] += 1
    for values in adj.values():
        values.sort()
    visited = {vertices[0]}
    stack = [vertices[0]]
    while stack:
        for v, _, _ in adj[stack.pop()]:
            if v not in visited:
                visited.add(v)
                stack.append(v)
    if len(visited) != len(vertices):
        raise ValueError("graph is disconnected")
    return vertices, sorted(clean), adj, degree


def shortest(adj, source):
    dist, parent = {source: 0}, {}
    heap = [(0, source)]
    while heap:
        cost, u = heappop(heap)
        if cost != dist[u]:
            continue
        for v, w, eid in adj[u]:
            candidate = cost + w
            if v not in dist or candidate < dist[v]:
                dist[v] = candidate
                parent[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, parent


def pairing(distance):
    k = len(distance)
    if k % 2 or k > LIMIT:
        raise ValueError("odd vertex count must be even and <= 16")

    @lru_cache(None)
    def dp(mask):
        if not mask:
            return 0
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        return min(
            distance[i][j] + dp(rest ^ (1 << j))
            for j in range(i + 1, k) if rest & (1 << j)
        )

    mask, pairs = (1 << k) - 1, []
    optimum = dp(mask)
    while mask:
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        for j in range(i + 1, k):
            if rest & (1 << j) and (
                distance[i][j] + dp(rest ^ (1 << j)) == dp(mask)
            ):
                pairs.append((i, j))
                mask = rest ^ (1 << j)
                break
    return optimum, pairs


def euler(vertices, instances, start):
    # instances: (instance_id, original_edge_id, u, v, weight)
    adj = {v: [] for v in vertices}
    lookup = {}
    for iid, eid, u, v, w in instances:
        lookup[iid] = (eid, w)
        adj[u].append((iid, v))
        adj[v].append((iid, u))
    for values in adj.values():
        values.sort(reverse=True)
    used, stack, reverse = set(), [(start, None)], []
    while stack:
        u = stack[-1][0]
        while adj[u] and adj[u][-1][0] in used:
            adj[u].pop()
        if adj[u]:
            iid, v = adj[u].pop()
            used.add(iid)
            stack.append((v, (iid, u, v)))
        else:
            _, incoming = stack.pop()
            if incoming is not None:
                reverse.append(incoming)
    if len(used) != len(instances):
        raise ValueError("unused edge instance")
    steps = []
    for seq, (iid, u, v) in enumerate(reversed(reverse)):
        eid, w = lookup[iid]
        steps.append((seq, iid, eid, u, v, w))
    return steps


def solve(vertices, edges, start=None):
    vertices, edges, adj, degree = prepare(vertices, edges)
    start = vertices[0] if start is None else start
    if start not in adj:
        raise ValueError("unknown start")
    odd = [v for v in vertices if degree[v] % 2]
    if len(odd) > LIMIT:
        raise ValueError("odd vertex count exceeds 16")
    paths = {v: shortest(adj, v) for v in odd}
    distance = [[paths[u][0][v] for v in odd] for u in odd]
    extra, chosen = pairing(distance)
    instances = [
        (iid, eid, u, v, w)
        for iid, (eid, u, v, w) in enumerate(edges, 1)
    ]
    by_id = {eid: (u, v, w) for eid, u, v, w in edges}
    pairs = []
    for i, j in chosen:
        source, target = odd[i], odd[j]
        reverse_path, cursor = [], target
        while cursor != source:
            previous, eid = paths[source][1][cursor]
            reverse_path.append(eid)
            cursor = previous
        edge_ids = list(reversed(reverse_path))
        pairs.append((source, target, paths[source][0][target], edge_ids))
        for eid in edge_ids:
            u, v, w = by_id[eid]
            instances.append((len(instances) + 1, eid, u, v, w))
    base = sum(w for _, _, _, w in edges)
    return {
        "start": start, "odd": odd, "pairs": pairs,
        "base": base, "extra": extra, "total": base + extra,
        "instances": instances,
        "steps": euler(vertices, instances, start),
    }


def replay(vertices, edges, start, steps, claimed_total):
    vertices, edges, _, _ = prepare(vertices, edges)
    if start not in vertices:
        raise ValueError("unknown start")
    if type(claimed_total) is not int or claimed_total < 0:
        raise ValueError("claimed total must be a nonnegative integer")
    by_id = {eid: (u, v, w) for eid, u, v, w in edges}
    covered, used_instances = set(), set()
    cursor, total = start, 0
    for expected, (seq, iid, eid, u, v, w) in enumerate(steps):
        if any(type(x) is not int for x in (seq, iid, eid, w)):
            raise ValueError("numeric step fields must be integers")
        if iid < 1:
            raise ValueError("instance ID must be positive")
        if seq != expected or iid in used_instances:
            raise ValueError("bad step order or repeated instance")
        if eid not in by_id:
            raise ValueError("unknown edge")
        a, b, actual_weight = by_id[eid]
        if u != cursor or (u, v) not in ((a, b), (b, a)):
            raise ValueError("discontinuous or invalid step")
        if w != actual_weight:
            raise ValueError("weight differs from snapshot")
        used_instances.add(iid)
        covered.add(eid)
        cursor, total = v, total + actual_weight
    if cursor != start or covered != set(by_id) or total != claimed_total:
        raise ValueError("not a closed covering route with claimed total")
    return {"covered": len(covered), "steps": len(steps), "total": total}

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

result = solve(VERTICES, EDGES)
print("odd =", result["odd"])
print("pairs =", result["pairs"])
print("cost =", result["base"], "+", result["extra"], "=", result["total"])
print("route =", [step[2] for step in result["steps"]])
print("replay =", replay(VERTICES, EDGES, "A",
                         result["steps"], result["total"]))

完整输出:

odd = ['A', 'B', 'C', 'D']
pairs = [('A', 'B', 1, [8]), ('C', 'D', 2, [3])]
cost = 26 + 3 = 29
route = [1, 2, 3, 4, 5, 9, 3, 6, 7, 8, 8]
replay = {'covered': 9, 'steps': 11, 'total': 29}

本例的下界分解是 26+3=29。配对路径确实只增加了编号 8 和 3 的副本,而回放读取的是原图权重,不信任每步自报的数字。若某一步写成了不存在的边,或把 A 到 B 的记录偷换成 A 到 D,都会被拒绝。

示例八:事务保存快照与路线,再独立读回

仅保存 edge_id 和总成本并不足以复现结果:路网若在明天调价,相同编号会指向不同费用。这里把求解时的顶点和原始边序列化为规范 JSON 快照,与运行记录一起保存,再把路线步骤存入子表。示例用内存数据库保持可重复;实际落盘只需更换连接路径,并落实快照不可修改的应用约定和备份策略。成本分解使用十进制文本存储,避免多条 64 位权重累加后超出 SQLite INTEGER 范围。

SHA-256 用来发现快照意外变化,不能认证谁写入了数据;有权限同时修改快照和摘要的人仍可生成一致的新值。对于有敌手的审计,需要另行管理签名、访问控制和可信日志。这里也不声称 SQL 外键就能证明几何连续性:外键保证步骤属于某次运行,业务回放器再验证真实端点和全部覆盖。

一次运行及其步骤放在同一个事务里。示例第二次写入故意制造重复顺序号,并检查父记录也已回滚,防止留下半条路线。Python 连接上下文管理器的提交与回滚语义见 sqlite3 官方文档;事务全有或全无的数据库保证见 SQLite 事务说明。上下文管理器不会替你关闭连接,因此程序最后仍显式 close。

import hashlib
import json
import sqlite3

LIMIT = 16
MAX_INT = 2**63 - 1

def prepare(vertices, edges):
    vertices = list(vertices)
    if not vertices or any(type(v) is not str or not v for v in vertices):
        raise ValueError("vertices must be nonempty strings")
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    vertices.sort()
    adj = {v: [] for v in vertices}
    degree = dict.fromkeys(vertices, 0)
    seen = set()
    clean = []
    for eid, u, v, w in edges:
        if type(eid) is not int or not 1 <= eid <= MAX_INT or eid in seen:
            raise ValueError("invalid or duplicate edge ID")
        if u not in adj or v not in adj:
            raise ValueError("unknown endpoint")
        if type(w) is not int or not 0 <= w <= MAX_INT:
            raise ValueError("weight must be a nonnegative 64-bit integer")
        seen.add(eid)
        clean.append((eid, u, v, w))
        adj[u].append((v, w, eid))
        adj[v].append((u, w, eid))
        degree[u] += 1
        degree[v] += 1
    for values in adj.values():
        values.sort()
    visited = {vertices[0]}
    stack = [vertices[0]]
    while stack:
        for v, _, _ in adj[stack.pop()]:
            if v not in visited:
                visited.add(v)
                stack.append(v)
    if len(visited) != len(vertices):
        raise ValueError("graph is disconnected")
    return vertices, sorted(clean), adj, degree

def replay(vertices, edges, start, steps, claimed_total):
    vertices, edges, _, _ = prepare(vertices, edges)
    if start not in vertices:
        raise ValueError("unknown start")
    if type(claimed_total) is not int or claimed_total < 0:
        raise ValueError("claimed total must be a nonnegative integer")
    by_id = {eid: (u, v, w) for eid, u, v, w in edges}
    covered, used_instances = set(), set()
    cursor, total = start, 0
    for expected, (seq, iid, eid, u, v, w) in enumerate(steps):
        if any(type(x) is not int for x in (seq, iid, eid, w)):
            raise ValueError("numeric step fields must be integers")
        if iid < 1:
            raise ValueError("instance ID must be positive")
        if seq != expected or iid in used_instances:
            raise ValueError("bad step order or repeated instance")
        if eid not in by_id:
            raise ValueError("unknown edge")
        a, b, actual_weight = by_id[eid]
        if u != cursor or (u, v) not in ((a, b), (b, a)):
            raise ValueError("discontinuous or invalid step")
        if w != actual_weight:
            raise ValueError("weight differs from snapshot")
        used_instances.add(iid)
        covered.add(eid)
        cursor, total = v, total + actual_weight
    if cursor != start or covered != set(by_id) or total != claimed_total:
        raise ValueError("not a closed covering route with claimed total")
    return {"covered": len(covered), "steps": len(steps), "total": total}

VERTICES = list('ABCD')
EDGES = [(1, 'A', 'B', 2), (2, 'B', 'C', 2), (3, 'C', 'D', 2), (4, 'D', 'A', 2), (5, 'A', 'C', 5), (6, 'B', 'D', 5), (7, 'A', 'B', 7), (8, 'A', 'B', 1), (9, 'C', 'C', 0)]

STEPS = [(0, 1, 1, 'A', 'B', 2), (1, 2, 2, 'B', 'C', 2), (2, 3, 3, 'C', 'D', 2), (3, 4, 4, 'D', 'A', 2), (4, 5, 5, 'A', 'C', 5), (5, 9, 9, 'C', 'C', 0), (6, 11, 3, 'C', 'D', 2), (7, 6, 6, 'D', 'B', 5), (8, 7, 7, 'B', 'A', 7), (9, 8, 8, 'A', 'B', 1), (10, 10, 8, 'B', 'A', 1)]

con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE run(
    run_id INTEGER PRIMARY KEY,
    snapshot_json TEXT NOT NULL,
    snapshot_sha256 TEXT NOT NULL,
    start TEXT NOT NULL,
    base_decimal TEXT NOT NULL,
    extra_decimal TEXT NOT NULL,
    total_decimal TEXT NOT NULL
);
CREATE TABLE step(
    run_id INTEGER NOT NULL REFERENCES run(run_id),
    seq INTEGER NOT NULL,
    instance_id INTEGER NOT NULL,
    edge_id INTEGER NOT NULL,
    src TEXT NOT NULL,
    dst TEXT NOT NULL,
    weight INTEGER NOT NULL,
    PRIMARY KEY(run_id, seq),
    UNIQUE(run_id, instance_id)
);
""")
snapshot = json.dumps(
    {"vertices": VERTICES, "edges": EDGES},
    ensure_ascii=False, sort_keys=True, separators=(",", ":"),
)
digest = hashlib.sha256(snapshot.encode("utf-8")).hexdigest()
with con:
    con.execute("INSERT INTO run VALUES(?,?,?,?,?,?,?)",
                (1, snapshot, digest, "A", "26", "3", "29"))
    con.executemany("INSERT INTO step VALUES(?,?,?,?,?,?,?)",
                    [(1, *step) for step in STEPS])
raw, saved_hash, start, base, extra, total = con.execute(
    "SELECT snapshot_json,snapshot_sha256,start,"
    "base_decimal,extra_decimal,total_decimal FROM run WHERE run_id=?",
    (1,),
).fetchone()
if hashlib.sha256(raw.encode("utf-8")).hexdigest() != saved_hash:
    raise ValueError("snapshot checksum mismatch")
frozen = json.loads(raw)
if int(base) + int(extra) != int(total):
    raise ValueError("cost decomposition mismatch")
if sum(edge[3] for edge in frozen["edges"]) != int(base):
    raise ValueError("base cost differs from snapshot")
saved_steps = con.execute(
    "SELECT seq,instance_id,edge_id,src,dst,weight "
    "FROM step WHERE run_id=? ORDER BY seq", (1,),
).fetchall()
print("snapshot checksum = OK")
print("replay =", replay(frozen["vertices"], frozen["edges"],
                         start, saved_steps, int(total)))
try:
    with con:
        con.execute("INSERT INTO run VALUES(?,?,?,?,?,?,?)",
                    (2, snapshot, digest, "A", "26", "3", "29"))
        con.execute("INSERT INTO step VALUES(?,?,?,?,?,?,?)",
                    (2, *STEPS[0]))
        con.execute("INSERT INTO step VALUES(?,?,?,?,?,?,?)",
                    (2, *STEPS[0]))
except sqlite3.IntegrityError:
    print("failed batch rolled back =", con.execute(
        "SELECT COUNT(*) FROM run WHERE run_id=2").fetchone()[0] == 0)
changed = list(saved_steps)
changed[0] = (*changed[0][:-1], 999)
try:
    replay(VERTICES, EDGES, "A", changed, 29)
except ValueError as error:
    print("tamper:", error)
con.close()

完整输出:

snapshot checksum = OK
replay = {'covered': 9, 'steps': 11, 'total': 29}
failed batch rolled back = True
tamper: weight differs from snapshot

正式系统还应把求解器版本、奇点上限和运行状态写入元数据。若原始数据来自正在变化的数据库,先在同一读事务里取出一致快照,再基于快照求解;不能让顶点表和边表分别来自两个不同时刻。发布给下游的记录应只有验证通过的完整运行。

示例九:用两种独立穷举击穿幸运样例

测试不能只拿上面的四点图反复断言 29。第一层穷举四个点的全部六个两两权重,每个取 0、1、2,共 729 张对称矩阵;直接列出所有完美配对,与动态规划比较。第二层枚举最多三个顶点、最多四条边、权重为 0 或 1 的全部边类型多重集合,允许自环和平行边。只接受全体声明顶点连通的输入,不连通图则确认求解器拒绝。

第二层的 oracle 不使用奇点配对,而是把状态定义为当前位置与已经访问的原始边位掩码。一次行走更新当前位置和覆盖集合,目标是在所有原始边都访问过后回到起点。对这个有限状态图求最短路,直接对应原始问题定义。它的状态数随着原始边数指数增长,因此只适合小图测试,不能拿来替代生产求解器。零权环不会导致测试不终止,因为只有严格改善状态代价时才重新入队。

from itertools import combinations, combinations_with_replacement, product

from functools import lru_cache
from heapq import heappop, heappush

LIMIT = 16
MAX_INT = 2**63 - 1


def prepare(vertices, edges):
    vertices = list(vertices)
    if not vertices or any(type(v) is not str or not v for v in vertices):
        raise ValueError("vertices must be nonempty strings")
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    vertices.sort()
    adj = {v: [] for v in vertices}
    degree = dict.fromkeys(vertices, 0)
    seen = set()
    clean = []
    for eid, u, v, w in edges:
        if type(eid) is not int or not 1 <= eid <= MAX_INT or eid in seen:
            raise ValueError("invalid or duplicate edge ID")
        if u not in adj or v not in adj:
            raise ValueError("unknown endpoint")
        if type(w) is not int or not 0 <= w <= MAX_INT:
            raise ValueError("weight must be a nonnegative 64-bit integer")
        seen.add(eid)
        clean.append((eid, u, v, w))
        adj[u].append((v, w, eid))
        adj[v].append((u, w, eid))
        degree[u] += 1
        degree[v] += 1
    for values in adj.values():
        values.sort()
    visited = {vertices[0]}
    stack = [vertices[0]]
    while stack:
        for v, _, _ in adj[stack.pop()]:
            if v not in visited:
                visited.add(v)
                stack.append(v)
    if len(visited) != len(vertices):
        raise ValueError("graph is disconnected")
    return vertices, sorted(clean), adj, degree


def shortest(adj, source):
    dist, parent = {source: 0}, {}
    heap = [(0, source)]
    while heap:
        cost, u = heappop(heap)
        if cost != dist[u]:
            continue
        for v, w, eid in adj[u]:
            candidate = cost + w
            if v not in dist or candidate < dist[v]:
                dist[v] = candidate
                parent[v] = (u, eid)
                heappush(heap, (candidate, v))
    return dist, parent


def pairing(distance):
    k = len(distance)
    if k % 2 or k > LIMIT:
        raise ValueError("odd vertex count must be even and <= 16")

    @lru_cache(None)
    def dp(mask):
        if not mask:
            return 0
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        return min(
            distance[i][j] + dp(rest ^ (1 << j))
            for j in range(i + 1, k) if rest & (1 << j)
        )

    mask, pairs = (1 << k) - 1, []
    optimum = dp(mask)
    while mask:
        bit = mask & -mask
        i = bit.bit_length() - 1
        rest = mask ^ bit
        for j in range(i + 1, k):
            if rest & (1 << j) and (
                distance[i][j] + dp(rest ^ (1 << j)) == dp(mask)
            ):
                pairs.append((i, j))
                mask = rest ^ (1 << j)
                break
    return optimum, pairs


def euler(vertices, instances, start):
    # instances: (instance_id, original_edge_id, u, v, weight)
    adj = {v: [] for v in vertices}
    lookup = {}
    for iid, eid, u, v, w in instances:
        lookup[iid] = (eid, w)
        adj[u].append((iid, v))
        adj[v].append((iid, u))
    for values in adj.values():
        values.sort(reverse=True)
    used, stack, reverse = set(), [(start, None)], []
    while stack:
        u = stack[-1][0]
        while adj[u] and adj[u][-1][0] in used:
            adj[u].pop()
        if adj[u]:
            iid, v = adj[u].pop()
            used.add(iid)
            stack.append((v, (iid, u, v)))
        else:
            _, incoming = stack.pop()
            if incoming is not None:
                reverse.append(incoming)
    if len(used) != len(instances):
        raise ValueError("unused edge instance")
    steps = []
    for seq, (iid, u, v) in enumerate(reversed(reverse)):
        eid, w = lookup[iid]
        steps.append((seq, iid, eid, u, v, w))
    return steps


def solve(vertices, edges, start=None):
    vertices, edges, adj, degree = prepare(vertices, edges)
    start = vertices[0] if start is None else start
    if start not in adj:
        raise ValueError("unknown start")
    odd = [v for v in vertices if degree[v] % 2]
    if len(odd) > LIMIT:
        raise ValueError("odd vertex count exceeds 16")
    paths = {v: shortest(adj, v) for v in odd}
    distance = [[paths[u][0][v] for v in odd] for u in odd]
    extra, chosen = pairing(distance)
    instances = [
        (iid, eid, u, v, w)
        for iid, (eid, u, v, w) in enumerate(edges, 1)
    ]
    by_id = {eid: (u, v, w) for eid, u, v, w in edges}
    pairs = []
    for i, j in chosen:
        source, target = odd[i], odd[j]
        reverse_path, cursor = [], target
        while cursor != source:
            previous, eid = paths[source][1][cursor]
            reverse_path.append(eid)
            cursor = previous
        edge_ids = list(reversed(reverse_path))
        pairs.append((source, target, paths[source][0][target], edge_ids))
        for eid in edge_ids:
            u, v, w = by_id[eid]
            instances.append((len(instances) + 1, eid, u, v, w))
    base = sum(w for _, _, _, w in edges)
    return {
        "start": start, "odd": odd, "pairs": pairs,
        "base": base, "extra": extra, "total": base + extra,
        "instances": instances,
        "steps": euler(vertices, instances, start),
    }


def replay(vertices, edges, start, steps, claimed_total):
    vertices, edges, _, _ = prepare(vertices, edges)
    if start not in vertices:
        raise ValueError("unknown start")
    if type(claimed_total) is not int or claimed_total < 0:
        raise ValueError("claimed total must be a nonnegative integer")
    by_id = {eid: (u, v, w) for eid, u, v, w in edges}
    covered, used_instances = set(), set()
    cursor, total = start, 0
    for expected, (seq, iid, eid, u, v, w) in enumerate(steps):
        if any(type(x) is not int for x in (seq, iid, eid, w)):
            raise ValueError("numeric step fields must be integers")
        if iid < 1:
            raise ValueError("instance ID must be positive")
        if seq != expected or iid in used_instances:
            raise ValueError("bad step order or repeated instance")
        if eid not in by_id:
            raise ValueError("unknown edge")
        a, b, actual_weight = by_id[eid]
        if u != cursor or (u, v) not in ((a, b), (b, a)):
            raise ValueError("discontinuous or invalid step")
        if w != actual_weight:
            raise ValueError("weight differs from snapshot")
        used_instances.add(iid)
        covered.add(eid)
        cursor, total = v, total + actual_weight
    if cursor != start or covered != set(by_id) or total != claimed_total:
        raise ValueError("not a closed covering route with claimed total")
    return {"covered": len(covered), "steps": len(steps), "total": total}

def all_matching_costs(matrix, remaining):
    if not remaining:
        yield 0
        return
    i = remaining[0]
    for pos in range(1, len(remaining)):
        j = remaining[pos]
        rest = remaining[1:pos] + remaining[pos + 1:]
        for suffix in all_matching_costs(matrix, rest):
            yield matrix[i][j] + suffix

matching_count = 0
slots = list(combinations(range(4), 2))
for weights in product(range(3), repeat=len(slots)):
    matrix = [[0] * 4 for _ in range(4)]
    for (i, j), w in zip(slots, weights):
        matrix[i][j] = matrix[j][i] = w
    expected = min(all_matching_costs(matrix, list(range(4))))
    assert pairing(matrix)[0] == expected
    matching_count += 1

def direct_closed_walk(vertices, edges):
    # Independent state: current vertex and visited ORIGINAL-edge bitmask.
    adj = {v: [] for v in vertices}
    for index, (_, u, v, w) in enumerate(edges):
        adj[u].append((v, w, 1 << index))
        adj[v].append((u, w, 1 << index))
    start = vertices[0]
    target = (1 << len(edges)) - 1
    best, queue = {(start, 0): 0}, [(0, start, 0)]
    while queue:
        cost, u, mask = heappop(queue)
        if cost != best[(u, mask)]:
            continue
        if u == start and mask == target:
            return cost
        for v, w, bit in adj[u]:
            state = (v, mask | bit)
            candidate = cost + w
            if state not in best or candidate < best[state]:
                best[state] = candidate
                heappush(queue, (candidate, *state))
    return None

graph_count = 0
for n in range(1, 4):
    vertices = list("ABC"[:n])
    types = [
        (u, v, w) for i, u in enumerate(vertices)
        for v in vertices[i:] for w in (0, 1)
    ]
    for size in range(5):
        for choices in combinations_with_replacement(types, size):
            edges = [(i + 1, *edge) for i, edge in enumerate(choices)]
            oracle = direct_closed_walk(vertices, edges)
            # The solver requires every declared vertex to be connected.
            reachable = {vertices[0]}
            while True:
                expanded = reachable | {
                    v for _, u, v, _ in edges if u in reachable
                } | {u for _, u, v, _ in edges if v in reachable}
                if expanded == reachable:
                    break
                reachable = expanded
            if len(reachable) != n:
                try:
                    solve(vertices, edges)
                except ValueError:
                    continue
                raise AssertionError("disconnected graph accepted")
            result = solve(vertices, edges)
            assert result["total"] == oracle
            replay(vertices, edges, vertices[0],
                   result["steps"], result["total"])
            graph_count += 1
print("exhaustive 4-vertex matching matrices =", matching_count)
print("connected multigraph route checks =", graph_count)
print("matching and direct-walk oracles = PASS")

for leaves in (16, 18):
    vertices = ["O"] + [f"L{i:02d}" for i in range(leaves)]
    edges = [(i + 1, "O", v, 1) for i, v in enumerate(vertices[1:])]
    try:
        result = solve(vertices, edges, start="O")
        print("odd =", leaves, "total =", result["total"])
    except ValueError as error:
        print("odd =", leaves, "rejected:", error)

完整输出:

exhaustive 4-vertex matching matrices = 729
connected multigraph route checks = 910
matching and direct-walk oracles = PASS
odd = 16 total = 32
odd = 18 rejected: odd vertex count exceeds 16

最后用星形图检查资源边界:16 个叶子产生 16 个奇点,可以得到精确答案;18 个叶子被明确拒绝。所有断言应在普通 Python 模式运行,不要使用会移除 assert 的 -O。穷举覆盖有限范围,不能代替证明,但能够有效抓出自环计度、平行边合并、路径副本去重和回溯方向等实现错误。

复杂度、容量规划与上线检查

设原图有 n 个顶点、m 条边、k 个奇点,增广后共有 m′ 个边实例。本实现从每个奇点运行一次惰性堆最短路,保守时间界可写成 O(k(n+m)log(n+m)),因为多重图中堆里可能同时存在多个过期候选;保存每个奇点的距离与前驱需要 O(kn) 空间,另有 O(m) 邻接存储。位掩码配对的宽松上界为 O(k²2^k) 时间、O(2^k) 状态空间,加上 O(k²) 距离矩阵;固定最低位会减少实际访问状态,但不能把指数部分说成多项式。

路径恢复在有限前驱链上进行,复制后产生 m′ 条实例。欧拉栈遍历本身是 O(n+m′),为获得稳定顺序所做的邻接排序另需至多 O(m′log m′)。因此不要把含排序的完整实现直接宣传为线性时间。设定 k≤16 只约束配对阶段,并不意味着任意大的原始路网都能在同样时间或内存里完成;上线仍需评估 m、最短路次数、复制路径长度和 SQLite 写入批次大小。

交付前建议逐项核对:输入是连通无向图;每条原始边有永久唯一编号;自环贡献二度;权重是非负整数;奇点数未超上限;配对中的每个奇点出现一次;副本仍能追溯到原始编号;路线的每一步连续、最终回到起点;所有原始边至少覆盖一次;回放费用等于原始总成本加精确配对值;保存的是同一时刻的图快照;失败写入不会留下部分记录。任何一项失败,都应把该次运行标为失败并返回清楚的原因。

中国邮差问题在这里提供的不是一串难以解释的路线,而是一条可以分层检查的计算链:原始任务成本给出不可避免的基础支出,奇点配对给出最低补走成本,路径副本把抽象匹配变回真实道路,欧拉遍历生成执行顺序,SQLite 快照与回放保住事后可核验性。把这几层边界写清楚,才有资格把最终数字称为精确最优值。

参考资料与可复现说明

以上资料于 2026 年 10 月 20 日核对。九段示例均无随机输入,不访问网络,不依赖第三方 Python 包;输出中的具体路线取决于本文规定的排序与选取顺序,而最优成本不依赖同价方案中选中了哪条。

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