Python + SQLite 实战:用 DSATUR 分支限界求小图色数,让预算、证书与最优性各有交代

10-20 6阅读

同一批任务之间有冲突,究竟最少需要几个互不冲突的批次?把任务当作顶点,把不能同批执行的关系当作无向边,这就是顶点着色问题。一个颜色代表一个批次,相邻顶点必须异色。真正难的不是给出一张能用的排班表,而是回答:还能不能少用一种颜色?本文用 Python 标准库实现一个有明确输入范围、搜索预算和证据语义的小图求解器,再把输入与结果一起保存到 SQLite,避免把“找到方案”误报成“已经证明最优”。

Python + SQLite 实战:用 DSATUR 分支限界求小图色数,让预算、证书与最优性各有交代
AI 概念图:彩色节点表示分组,分层档案表示结果快照,分支表示搜索。该图仅作概念说明,不作为合法着色或搜索过程的数学证据。

这里的精确,是指程序只有在上下界相遇,或者所有可能改进当前解的分支都已排除时,才返回 optimal。预算耗尽则返回 budget_exhausted,同时保留有效方案和仍然可信的区间。本文不声称 DSATUR 对一般图能在多项式时间内求出色数,也不把 SQLite 当成能消除组合爆炸的搜索引擎。

全部九个示例均可分别复制为一个 Python 文件直接运行,不依赖前一个示例定义的变量、不读取外部数据,也不安装第三方包。为保证独立运行,后面的示例会完整重复求解器。实测环境为 Python 3.12.14 与 SQLite 3.53.1;演示数据库使用内存或自动清理的临时目录,不覆盖现有数据库。

一、先收紧问题边界:最多 18 个顶点的简单无向图

顶点严格编号为 0 到 n−1,n 允许为零,空图的色数约定为零。本文主动限制 n≤18,并限制最多接受 10000 条原始边;这些是教学实现的资源护栏,不是“18 个顶点一定容易”的复杂度结论。相同端点的重复边以及反向重复边合并为一条;自环直接拒绝,因为自环要求一个顶点与自身异色,普通顶点着色无解。孤立顶点必须保留,所以不能仅从边表推导顶点集合。

输入的端点必须是真正的整数,而不是浮点数或布尔值。Python 中布尔值属于整数的子类,代码使用 type(x) is int,避免把 True 悄悄当作顶点 1。边先规范成较小端点在前,再排序;这样数据库输入顺序与集合的内部遍历次序都不会改变后面的结果。非法边的形状也不会被静默忽略,而会在解包或检查时抛出异常。

示例 1 把四个顶点和去重后的边写入 SQLite。外键在当前连接上显式启用,值通过参数绑定传入 SQL;顶点表保存孤立点,边表保存规范方向。这里的表约束是第二道防线,入口的图校验仍然不能省略。外键开关属于连接级设置,另开连接时应重新设置。参数绑定与事务接口可参阅 Python sqlite3 官方文档,外键行为见 SQLite 官方说明。

MAX_N = 18
MAX_RAW_EDGES = 10000

def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj

import sqlite3

edges, _ = graph(4, [(2, 1), (0, 1), (1, 2), (3, 2)])
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),
    PRIMARY KEY(u, v), CHECK(u < v)
);
""")
with con:
    con.executemany("INSERT INTO vertex VALUES(?)", [(i,) for i in range(4)])
    con.executemany("INSERT INTO edge VALUES(?, ?)", edges)
print(con.execute("SELECT u, v FROM edge ORDER BY u, v").fetchall())
print(con.execute("SELECT count(*) FROM vertex").fetchone()[0])
try:
    graph(2, [(1, 1)])
except ValueError as exc:
    print(str(exc))
con.close()

确定输出:

[(0, 1), (1, 2), (2, 3)]
4
self-loop is not supported

二、先验证证书,再讨论“最少”

色数记作 χ(G)。如果给定一份使用 U 种颜色的完整合法着色,我们知道 χ(G)≤U。这是上界证据:逐个检查顶点是否获得合法颜色,再检查每条边的两个端点是否异色即可。这个检查不需要重跑搜索。相反,仅凭三种颜色的一份方案,不能推出两种颜色一定不够。把一个颜色数组命名为 optimal_colors,并不会让它自动具有最优性。

示例 2 的校验器只接收已经经过 graph 规范化的图。它要求颜色编号恰好覆盖 0 到 k−1;通过“编号在范围内”和“实际使用了 k 种”这两条检查,排除多报颜色数、遗漏顶点、负数编号以及布尔颜色。工程中应让所有外部输入先走规范化入口,不能把这个精简校验器误当成完整的图文件解析器。五边形的第一个数组合法,第二个数组在闭合边上发生冲突。

MAX_N = 18
MAX_RAW_EDGES = 10000

def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def valid_coloring(n, edges, colors, k):
    if type(k) is not int or k < 0 or len(colors) != n:
        return False
    if any(type(c) is not int or not 0 <= c < k for c in colors):
        return False
    return len(set(colors)) == k and all(colors[u] != colors[v] for u, v in edges)

edges, _ = graph(5, [(i, (i + 1) % 5) for i in range(5)])
print(valid_coloring(5, edges, [0, 1, 0, 1, 2], 3))
print(valid_coloring(5, edges, [0, 1, 0, 1, 0], 2))
print(valid_coloring(5, edges, [0, 1], 2))
print(valid_coloring(0, [], [], 0))

确定输出:

True
False
False
True

三、DSATUR 负责选择顺序,贪心只负责给上界

一个尚未着色的顶点,其饱和度是已着色邻居中不同颜色的数量。三个邻居都涂成蓝色,饱和度仍然只有一;这和邻居数量不是一回事。选择饱和度高的顶点,通常能更早暴露受到限制的位置。Brélaz 的原始论文给出了这一思想以及精确搜索方法,见 New Methods to Color the Vertices of a Graph(1979)。本文采用便于复现的教学变体,并非逐行复刻原论文。

本文的平局规则固定为:饱和度降序、原图总度数降序、顶点编号升序。注意第二项是原图总度数,不是当前未着色子图中的度数。颜色尝试顺序为从零开始的升序。这个约定同时用于初始贪心和后面的分支搜索;只要图与预算不变,节点访问计数和结果也可重复。换一种平局策略可能影响速度和初始上界,却不能改变合法性与精确搜索的目标。

示例 3 刻意不选一个贪心恰好最优的简单图。这个七顶点图的贪心结果用了四种颜色,而示例 5 会找到三色方案并证明最优。这样的反例比一句“贪心不保证最优”更有用:读者可以检查同一张图、同一套确定规则,亲眼看到启发式方案与色数之间的距离。

MAX_N = 18
MAX_RAW_EDGES = 10000

def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def pick(adj, colors):
    def key(v):
        saturation = len({colors[u] for u in adj[v] if colors[u] >= 0})
        return saturation, len(adj[v]), -v
    return max((v for v in range(len(adj)) if colors[v] < 0), key=key)


def greedy(adj):
    colors = [-1] * len(adj)
    for _ in adj:
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        c = 0
        while c in forbidden:
            c += 1
        colors[v] = c
    return tuple(colors)

edges = [(0, 1), (0, 3), (0, 6), (1, 4), (1, 6),
         (2, 3), (2, 4), (2, 5), (3, 5), (4, 5)]
_, adj = graph(7, edges)
colors = greedy(adj)
print(colors)
print("greedy upper =", len(set(colors)))
print(colors == greedy(graph(7, list(reversed(edges)))[1]))

确定输出:

(0, 1, 0, 1, 2, 3, 2)
greedy upper = 4
True

四、团给出可核验的下界,但不必求最大团

如果一组 L 个顶点两两相邻,它们必须两两异色,因此 χ(G)≥L。我们保存这些顶点本身作为团见证,再检查任意一对顶点之间都有边。这里实现的是按总度数排序后逐个扩展的贪心团,不是最大团算法;它返回的见证可能很小,但只要确实构成团,下界就合法。为了得到一个下界而先完整求解最大团,可能只是把一个昂贵问题换成另一个昂贵问题。

五边形很好地揭示了证据的局限:它存在大小为二的团,但不存在三角形;它的色数却是三。因此“团没有再变大”不能作为终止搜索的理由。只有团大小与合法着色使用的颜色数相同,才可以直接夹出色数。示例 4 输出的二是有效下界,并没有宣称它独自证明五边形只需两种颜色。

MAX_N = 18
MAX_RAW_EDGES = 10000

def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def clique_witness(adj):
    clique = []
    for v in sorted(range(len(adj)), key=lambda v: (-len(adj[v]), v)):
        if all(v in adj[u] for u in clique):
            clique.append(v)
    return tuple(clique)

from itertools import combinations

edges, adj = graph(5, [(i, (i + 1) % 5) for i in range(5)])
witness = clique_witness(adj)
print("clique =", witness)
print("verified =", all(v in adj[u] for u, v in combinations(witness, 2)))
print("lower =", len(witness))

确定输出:

clique = (0, 1)
verified = True
lower = 2

五、分支限界:遍历可能改进上界的规范化着色

现在组合上界与下界。起始上界来自完整贪心着色,下界来自团见证。搜索状态只保存部分着色和已经使用的颜色数 used。每次通过 DSATUR 选择下一个顶点,先尝试已有颜色;若还可能改善上界,再尝试一个新的颜色 used。新的颜色只开一个,避免把仅仅交换颜色名称的方案重复枚举。

为什么这种颜色对称性消除不会漏掉更好的答案?任意完整着色都可以按搜索过程中颜色首次出现的顺序重新编号。下一步遇到的新颜色总能改名为 used,其余颜色名字不影响相邻顶点是否相同,也不影响饱和度和本文的顶点选择规则。因此同一个颜色分组至少保留一个规范代表。

剪枝也要对应明确理由。若当前已经用到的颜色数不小于最好的完整方案,继续扩展不可能减少这些颜色,故无需深入;若上界已经等于团下界,最优性已经成立,可以全局停止。其余可能改善上界的合法选择必须全部检查。代码没有把“某个顶点暂时颜色很多”直接当成全局下界,也没有把一次回溯失败当成全图不可着色。

示例 5 是完整求解器。搜索过程中保存的 best 始终是完整合法方案,从不把当前 colors 这个半成品返回给调用方。中断会通过标记逐层退出,并在返回前撤销当前赋色;新的 best 通过 tuple 拷贝,避免回溯操作把已保存方案改坏。程序最终再次验证证书,给返回值加上一道运行时自检。

# Python 3.11+, only the standard library.
MAX_N = 18
MAX_RAW_EDGES = 10000


def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def valid_coloring(n, edges, colors, k):
    if type(k) is not int or k < 0 or len(colors) != n:
        return False
    if any(type(c) is not int or not 0 <= c < k for c in colors):
        return False
    return len(set(colors)) == k and all(colors[u] != colors[v] for u, v in edges)


def pick(adj, colors):
    def key(v):
        saturation = len({colors[u] for u in adj[v] if colors[u] >= 0})
        return saturation, len(adj[v]), -v
    return max((v for v in range(len(adj)) if colors[v] < 0), key=key)


def greedy(adj):
    colors = [-1] * len(adj)
    for _ in adj:
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        c = 0
        while c in forbidden:
            c += 1
        colors[v] = c
    return tuple(colors)


def clique_witness(adj):
    clique = []
    for v in sorted(range(len(adj)), key=lambda v: (-len(adj[v]), v)):
        if all(v in adj[u] for u in clique):
            clique.append(v)
    return tuple(clique)


def solve(n, edges, budget=100000):
    if type(budget) is not int or budget < 0:
        raise ValueError("budget must be a nonnegative integer")
    edges, adj = graph(n, edges)
    best = greedy(adj)
    upper = len(set(best))
    clique = clique_witness(adj)
    lower = len(clique)
    colors = [-1] * n
    nodes = 0
    interrupted = False

    def dfs(used):
        nonlocal best, upper, nodes, interrupted
        if upper == lower or used >= upper:
            return
        if -1 not in colors:
            best, upper = tuple(colors), used
            return
        if nodes >= budget:
            interrupted = True
            return
        nodes += 1
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        # Existing colors first; at most one canonical new color.
        for c in range(min(used + 1, upper)):
            if c in forbidden:
                continue
            colors[v] = c
            dfs(max(used, c + 1))
            colors[v] = -1
            if interrupted or upper == lower:
                return

    dfs(0)
    if upper == lower:
        status, reason = "optimal", "bounds_match"
    elif interrupted:
        status, reason = "budget_exhausted", "node_budget"
    else:
        lower = upper
        status, reason = "optimal", "search_exhausted"
    assert valid_coloring(n, edges, best, upper)
    return dict(status=status, lower=lower, upper=upper,
                colors=list(best), clique=list(clique), nodes=nodes,
                budget=budget, reason=reason)

edges = [(0, 1), (0, 3), (0, 6), (1, 4), (1, 6),
         (2, 3), (2, 4), (2, 5), (3, 5), (4, 5)]
result = solve(7, edges)
print(result["status"], result["lower"], result["upper"], result["reason"])
print(result["colors"])
print("nodes =", result["nodes"])

确定输出:

optimal 3 3 bounds_match
[0, 1, 0, 2, 2, 1, 2]
nodes = 12

四种颜色降到三种后,保存的三顶点团也给出了下界三,所以本次 reason 为 bounds_match。若没有找到同样大的团,只要搜索已经完整排除了所有少于当前上界的方案,也可以把下界提升到上界,并报告 search_exhausted。后一种结论依赖搜索过程的正确性;它不是由那份较小的团见证独立证明的。

六、预算用完之后,答案必须仍然诚实

预算的单位是“展开的非完整搜索状态”,不是递归调用次数,更不是毫秒。代码先处理已被界剪掉的状态和完整方案,再在展开新状态之前检查预算;因此 nodes 永远不超过 budget。没有生成任何搜索节点也可能已经证明最优,例如三角形的团与三色贪心上界直接相遇。相反,五边形在零预算下只能报告区间 [2,3]。

示例 6 展示边界恰好差一个节点的情况:预算四时搜索尚未完成,不能因为已经接近结束就把状态改成 optimal;预算五时所有改进分支已排除,才能把区间收紧到 [3,3]。同样一份三色方案,可以在不同预算下具有不同的证明状态。客户端应同时展示 status、lower、upper 和 reason,而不是只看颜色数组。

# Python 3.11+, only the standard library.
MAX_N = 18
MAX_RAW_EDGES = 10000


def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def valid_coloring(n, edges, colors, k):
    if type(k) is not int or k < 0 or len(colors) != n:
        return False
    if any(type(c) is not int or not 0 <= c < k for c in colors):
        return False
    return len(set(colors)) == k and all(colors[u] != colors[v] for u, v in edges)


def pick(adj, colors):
    def key(v):
        saturation = len({colors[u] for u in adj[v] if colors[u] >= 0})
        return saturation, len(adj[v]), -v
    return max((v for v in range(len(adj)) if colors[v] < 0), key=key)


def greedy(adj):
    colors = [-1] * len(adj)
    for _ in adj:
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        c = 0
        while c in forbidden:
            c += 1
        colors[v] = c
    return tuple(colors)


def clique_witness(adj):
    clique = []
    for v in sorted(range(len(adj)), key=lambda v: (-len(adj[v]), v)):
        if all(v in adj[u] for u in clique):
            clique.append(v)
    return tuple(clique)


def solve(n, edges, budget=100000):
    if type(budget) is not int or budget < 0:
        raise ValueError("budget must be a nonnegative integer")
    edges, adj = graph(n, edges)
    best = greedy(adj)
    upper = len(set(best))
    clique = clique_witness(adj)
    lower = len(clique)
    colors = [-1] * n
    nodes = 0
    interrupted = False

    def dfs(used):
        nonlocal best, upper, nodes, interrupted
        if upper == lower or used >= upper:
            return
        if -1 not in colors:
            best, upper = tuple(colors), used
            return
        if nodes >= budget:
            interrupted = True
            return
        nodes += 1
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        # Existing colors first; at most one canonical new color.
        for c in range(min(used + 1, upper)):
            if c in forbidden:
                continue
            colors[v] = c
            dfs(max(used, c + 1))
            colors[v] = -1
            if interrupted or upper == lower:
                return

    dfs(0)
    if upper == lower:
        status, reason = "optimal", "bounds_match"
    elif interrupted:
        status, reason = "budget_exhausted", "node_budget"
    else:
        lower = upper
        status, reason = "optimal", "search_exhausted"
    assert valid_coloring(n, edges, best, upper)
    return dict(status=status, lower=lower, upper=upper,
                colors=list(best), clique=list(clique), nodes=nodes,
                budget=budget, reason=reason)

cycle = [(i, (i + 1) % 5) for i in range(5)]
for budget in (0, 4, 5):
    r = solve(5, cycle, budget)
    print(budget, r["status"], r["lower"], r["upper"], r["nodes"], r["reason"])
print("triangle:", solve(3, [(0, 1), (1, 2), (0, 2)], 0)["status"])
for n, budget in [(19, 1), (1, -1), (1, True)]:
    try:
        solve(n, [], budget)
    except ValueError as exc:
        print(str(exc))

确定输出:

0 budget_exhausted 2 3 0 node_budget
4 budget_exhausted 2 3 4 node_budget
5 optimal 3 3 5 search_exhausted
triangle: optimal
n must be an integer in 0..18
budget must be a nonnegative integer
budget must be a nonnegative integer

预算耗尽不等于不可行。这个模型对所有没有自环的有限图都能用至多 n 种颜色着色,而程序在搜索开始前已经找到一个合法上界。这里的不确定性在于最少需要几种颜色。如果业务问“最多 k 批是否足够”,upper≤k 已能回答足够,lower>k 已能回答不够;当 lower≤k<upper 时,只能回答尚未确定。

节点预算也不等于整个函数的严格时间上限。输入校验、贪心着色、构造团以及结果验证发生在预算控制的搜索之外;操作系统调度与 SQLite I/O 也不受这个计数器限制。需要硬超时的服务应在进程层设置取消机制,并设计好中断后的结果传递。一般图的搜索树仍可能指数增长,n≤18 不能保证所有实例在默认十万个节点内证得最优。

七、保存结果快照:输入、证据与证明状态要一起入库

只保存“这张图需要三种颜色”是不够的。边集合改变以后,旧结果可能仍然格式正确,却已经对应另一道题。示例 7 将规范化输入序列化为固定排序的 JSON,计算 SHA-256,再连同算法版本、预算、节点数、颜色证书、团见证和结论写入同一行。写入通过一个事务完成,避免输入已落盘但结果只写了一半的应用层状态。演示用内存库;改用专用数据库路径即可持久化。

读取时先校验输入摘要,再重建图和验证颜色。SHA-256 在这里用于发现意外变更与绑定输入,不提供身份认证:有写权限的人可以同时修改内容和摘要。更新、删除和重复编号插入的触发器只是防止应用误改记录的护栏,不是对拥有数据库管理权限者的防篡改保证。重复编号插入也要拦截,因为不能只靠删除触发器阻止 INSERT OR REPLACE 替换已有行。需要审计级真实性时,应另外设计访问控制、签名和可信存储。

SQL 的区间约束只能检查数字关系,不能证明最优。示例特意保存五边形的 search_exhausted 结果:重新读取后,颜色与团检查只验证它们各自的证据;接着按同一算法与预算重跑搜索,比较完整结果,才重新检查这次最优性结论。若 reason 是 bounds_match,验证一个同样大小的团和合法着色即可构成更短的最优性证明。

# Python 3.11+, only the standard library.
MAX_N = 18
MAX_RAW_EDGES = 10000


def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def valid_coloring(n, edges, colors, k):
    if type(k) is not int or k < 0 or len(colors) != n:
        return False
    if any(type(c) is not int or not 0 <= c < k for c in colors):
        return False
    return len(set(colors)) == k and all(colors[u] != colors[v] for u, v in edges)


def pick(adj, colors):
    def key(v):
        saturation = len({colors[u] for u in adj[v] if colors[u] >= 0})
        return saturation, len(adj[v]), -v
    return max((v for v in range(len(adj)) if colors[v] < 0), key=key)


def greedy(adj):
    colors = [-1] * len(adj)
    for _ in adj:
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        c = 0
        while c in forbidden:
            c += 1
        colors[v] = c
    return tuple(colors)


def clique_witness(adj):
    clique = []
    for v in sorted(range(len(adj)), key=lambda v: (-len(adj[v]), v)):
        if all(v in adj[u] for u in clique):
            clique.append(v)
    return tuple(clique)


def solve(n, edges, budget=100000):
    if type(budget) is not int or budget < 0:
        raise ValueError("budget must be a nonnegative integer")
    edges, adj = graph(n, edges)
    best = greedy(adj)
    upper = len(set(best))
    clique = clique_witness(adj)
    lower = len(clique)
    colors = [-1] * n
    nodes = 0
    interrupted = False

    def dfs(used):
        nonlocal best, upper, nodes, interrupted
        if upper == lower or used >= upper:
            return
        if -1 not in colors:
            best, upper = tuple(colors), used
            return
        if nodes >= budget:
            interrupted = True
            return
        nodes += 1
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        # Existing colors first; at most one canonical new color.
        for c in range(min(used + 1, upper)):
            if c in forbidden:
                continue
            colors[v] = c
            dfs(max(used, c + 1))
            colors[v] = -1
            if interrupted or upper == lower:
                return

    dfs(0)
    if upper == lower:
        status, reason = "optimal", "bounds_match"
    elif interrupted:
        status, reason = "budget_exhausted", "node_budget"
    else:
        lower = upper
        status, reason = "optimal", "search_exhausted"
    assert valid_coloring(n, edges, best, upper)
    return dict(status=status, lower=lower, upper=upper,
                colors=list(best), clique=list(clique), nodes=nodes,
                budget=budget, reason=reason)

import hashlib
import json
import sqlite3
from itertools import combinations


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"))


n = 5
edges, _ = graph(n, [(i, (i + 1) % 5) for i in range(5)])
result = solve(n, edges, 100)
input_json = canonical({"n": n, "edges": edges})
digest = hashlib.sha256(input_json.encode("utf-8")).hexdigest()
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE run(
    id INTEGER PRIMARY KEY,
    algorithm TEXT NOT NULL,
    input_json TEXT NOT NULL,
    input_sha256 TEXT NOT NULL,
    result_json TEXT NOT NULL,
    status TEXT NOT NULL CHECK(status IN ('optimal', 'budget_exhausted')),
    lower_bound INTEGER NOT NULL CHECK(lower_bound >= 0),
    upper_bound INTEGER NOT NULL CHECK(upper_bound >= lower_bound),
    CHECK(status != 'optimal' OR lower_bound = upper_bound)
);
CREATE TRIGGER immutable_run_insert BEFORE INSERT ON run
WHEN EXISTS(SELECT 1 FROM run WHERE id = NEW.id)
BEGIN SELECT RAISE(ABORT, 'duplicate snapshot id'); END;
CREATE TRIGGER immutable_run_update BEFORE UPDATE ON run
BEGIN SELECT RAISE(ABORT, 'immutable snapshot'); END;
CREATE TRIGGER immutable_run_delete BEFORE DELETE ON run
BEGIN SELECT RAISE(ABORT, 'immutable snapshot'); END;
""")
with con:
    con.execute("INSERT INTO run VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
                (1, "dsatur-bb-total-degree-v1", input_json, digest,
                 canonical(result), result["status"], result["lower"], result["upper"]))
raw, expected_hash, saved = con.execute(
    "SELECT input_json, input_sha256, result_json FROM run WHERE id = ?", (1,)
).fetchone()
assert hashlib.sha256(raw.encode("utf-8")).hexdigest() == expected_hash
payload, saved = json.loads(raw), json.loads(saved)
edges, adj = graph(payload["n"], payload["edges"])
clique = saved["clique"]
assert len(clique) == len(set(clique))
assert all(type(v) is int and 0 <= v < payload["n"] for v in clique)
assert all(v in adj[u] for u, v in combinations(clique, 2))
print("certificate:", valid_coloring(payload["n"], edges, saved["colors"], saved["upper"]))
# The saved status is a claim; replay the exact search to recheck optimality.
replay = solve(payload["n"], edges, saved["budget"])
assert replay == saved
print("replay:", replay["status"], replay["upper"])
try:
    with con:
        con.execute("UPDATE run SET upper_bound = 4 WHERE id = 1")
except sqlite3.IntegrityError as exc:
    print(str(exc))
try:
    with con:
        con.execute("INSERT OR REPLACE INTO run SELECT * FROM run WHERE id = 1")
except sqlite3.IntegrityError as exc:
    print(str(exc))
print("rows:", con.execute("SELECT count(*) FROM run").fetchone()[0])
con.close()

确定输出:

certificate: True
replay: optimal 3
immutable snapshot
duplicate snapshot id
rows: 1

这是一份输入和结果的快照,不是搜索前沿检查点。代码没有保存递归栈、下一分支索引或待探索状态,所以重新打开数据库后执行的是重跑,而不是从上次第几个节点继续。若要实现断点续算,必须另外定义前沿序列化、算法版本迁移以及重复执行规则;仅存一个 nodes 数字无法恢复当时的搜索位置。

八、读取实时图时,避免把两个版本拼成一个输入

上一节假设图已经在内存里稳定下来。实际程序往往先查询顶点数量,再查询边集合;如果两次查询之间有人提交修改,就可能把旧顶点数与新边集合拼接起来。解决思路不是在搜索全程锁住数据库,而是在一个短读取事务中一次性收集完整输入,然后结束事务,再对内存中的不可变副本求解。

示例 8 使用两个连接和 WAL 模式。读取连接显式 BEGIN 后执行第一次 SELECT,建立该事务看到的历史视图;写连接随后提交新增顶点和边。读取连接在同一个事务中继续查询时,仍然看到旧版本;结束事务并重新开始后,才读到新版本。这里强调的是 SQLite 的事务快照,与上一节应用自己保存的结果记录不是同一个概念。参阅 SQLite 隔离说明 与 事务文档。

import sqlite3
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as directory:
    path = Path(directory) / "graph.db"
    writer = sqlite3.connect(path, isolation_level=None)
    assert writer.execute("PRAGMA journal_mode = WAL").fetchone()[0] == "wal"
    writer.executescript("""
    CREATE TABLE meta(n INTEGER NOT NULL);
    INSERT INTO meta VALUES(3);
    CREATE TABLE edge(u INTEGER, v INTEGER, PRIMARY KEY(u, v));
    INSERT INTO edge VALUES(0, 1), (1, 2);
    """)
    reader = sqlite3.connect(path, isolation_level=None)
    try:
        reader.execute("BEGIN")
        n = reader.execute("SELECT n FROM meta").fetchone()[0]
        writer.execute("BEGIN IMMEDIATE")
        writer.execute("UPDATE meta SET n = ?", (4,))
        writer.execute("INSERT INTO edge VALUES(?, ?)", (2, 3))
        writer.execute("COMMIT")
        edges = reader.execute("SELECT u, v FROM edge ORDER BY u, v").fetchall()
        reader.execute("COMMIT")
        print("snapshot:", n, edges)
        reader.execute("BEGIN")
        latest_n = reader.execute("SELECT n FROM meta").fetchone()[0]
        latest_m = reader.execute("SELECT count(*) FROM edge").fetchone()[0]
        reader.execute("COMMIT")
        print("latest:", latest_n, latest_m)
    finally:
        if reader.in_transaction:
            reader.execute("ROLLBACK")
        if writer.in_transaction:
            writer.execute("ROLLBACK")
        reader.close()
        writer.close()

确定输出:

snapshot: 3 [(0, 1), (1, 2)]
latest: 4 3

不要把 WAL 理解成无限制并发写:它允许读写并行,但仍需要处理写入竞争、锁等待与异常回滚。示例让每个连接只在创建它的线程使用,最后显式关闭;真实服务也不应为了几秒甚至更久的组合搜索一直维持读取事务,否则会拉长历史版本的保留时间。读取事务只负责形成一致输入,搜索预算负责控制后续计算,两者各有边界。

九、用独立暴力 oracle 检查,而不是只跑几个经典图

三角形和五边形能帮助理解,却很难发现所有边界错误。示例 9 枚举零到五个顶点的全部带标号简单图,共 1100 张;对每张图,用与 DSATUR 无关的笛卡尔积枚举颜色数组,从一种颜色起逐个尝试,得到暴力 oracle。它不使用团剪枝、不使用动态顶点顺序,也不使用本文的颜色对称性规则,因此更适合当作独立比较对象。

每张图再跑六种预算,共 6600 次检查。重点不只是充分预算时结果等于 oracle,还要确认任何预算下 lower≤真实色数≤upper、返回的颜色证书合法、节点数不超预算,以及所有标成 optimal 的结果确实最优。预算为零的结果也必须参与;很多虚假的“精确求解器”恰好会在这条路径上误把初始贪心当成最优解。

# Python 3.11+, only the standard library.
MAX_N = 18
MAX_RAW_EDGES = 10000


def graph(n, edges):
    if type(n) is not int or not 0 <= n <= MAX_N:
        raise ValueError("n must be an integer in 0..18")
    clean = set()
    for count, edge in enumerate(edges, 1):
        if count > MAX_RAW_EDGES:
            raise ValueError("too many raw edges")
        u, v = edge
        if any(type(x) is not int or not 0 <= x < n for x in (u, v)):
            raise ValueError("invalid endpoint")
        if u == v:
            raise ValueError("self-loop is not supported")
        clean.add((min(u, v), max(u, v)))
    edges = tuple(sorted(clean))
    adj = [set() for _ in range(n)]
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    return edges, adj


def valid_coloring(n, edges, colors, k):
    if type(k) is not int or k < 0 or len(colors) != n:
        return False
    if any(type(c) is not int or not 0 <= c < k for c in colors):
        return False
    return len(set(colors)) == k and all(colors[u] != colors[v] for u, v in edges)


def pick(adj, colors):
    def key(v):
        saturation = len({colors[u] for u in adj[v] if colors[u] >= 0})
        return saturation, len(adj[v]), -v
    return max((v for v in range(len(adj)) if colors[v] < 0), key=key)


def greedy(adj):
    colors = [-1] * len(adj)
    for _ in adj:
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        c = 0
        while c in forbidden:
            c += 1
        colors[v] = c
    return tuple(colors)


def clique_witness(adj):
    clique = []
    for v in sorted(range(len(adj)), key=lambda v: (-len(adj[v]), v)):
        if all(v in adj[u] for u in clique):
            clique.append(v)
    return tuple(clique)


def solve(n, edges, budget=100000):
    if type(budget) is not int or budget < 0:
        raise ValueError("budget must be a nonnegative integer")
    edges, adj = graph(n, edges)
    best = greedy(adj)
    upper = len(set(best))
    clique = clique_witness(adj)
    lower = len(clique)
    colors = [-1] * n
    nodes = 0
    interrupted = False

    def dfs(used):
        nonlocal best, upper, nodes, interrupted
        if upper == lower or used >= upper:
            return
        if -1 not in colors:
            best, upper = tuple(colors), used
            return
        if nodes >= budget:
            interrupted = True
            return
        nodes += 1
        v = pick(adj, colors)
        forbidden = {colors[u] for u in adj[v] if colors[u] >= 0}
        # Existing colors first; at most one canonical new color.
        for c in range(min(used + 1, upper)):
            if c in forbidden:
                continue
            colors[v] = c
            dfs(max(used, c + 1))
            colors[v] = -1
            if interrupted or upper == lower:
                return

    dfs(0)
    if upper == lower:
        status, reason = "optimal", "bounds_match"
    elif interrupted:
        status, reason = "budget_exhausted", "node_budget"
    else:
        lower = upper
        status, reason = "optimal", "search_exhausted"
    assert valid_coloring(n, edges, best, upper)
    return dict(status=status, lower=lower, upper=upper,
                colors=list(best), clique=list(clique), nodes=nodes,
                budget=budget, reason=reason)

from itertools import combinations, product


def oracle(n, edges):
    if n == 0:
        return 0
    for k in range(1, n + 1):
        for colors in product(range(k), repeat=n):
            if all(colors[u] != colors[v] for u, v in edges):
                return k
    raise AssertionError("unreachable")


graphs = checks = 0
for n in range(6):
    possible = list(combinations(range(n), 2))
    for mask in range(1 << len(possible)):
        edges = [e for i, e in enumerate(possible) if mask & (1 << i)]
        truth = oracle(n, edges)
        graphs += 1
        for budget in (0, 1, 2, 3, 5, 100000):
            r = solve(n, edges, budget)
            assert r["lower"] <= truth <= r["upper"]
            assert valid_coloring(n, edges, r["colors"], r["upper"])
            assert r["nodes"] <= budget
            if r["status"] == "optimal":
                assert r["lower"] == truth == r["upper"]
            else:
                assert r["lower"] < r["upper"]
            if budget == 100000:
                assert r["status"] == "optimal"
            checks += 1
print("graphs:", graphs)
print("budget checks:", checks)
print("oracle: PASS")

确定输出:

graphs: 1100
budget checks: 6600
oracle: PASS

穷举小图不能替代对算法的完备性论证,它只能对实现提供有限范围的强回归证据。本实现还应测试空图、纯孤立点、完全图、断开分量、反向重复边、非法端点、自环、负预算和顶点数量超限;修改平局规则或剪枝逻辑以后,要重新生成节点计数与示例输出。性能测试则应把搜索节点数与总耗时分开记录,不能拿一张容易图的毫秒数承诺所有输入。

结语:把“能用”“最少”和“已核验”分开记录

一个可靠的小图着色服务,输出不该只是颜色列表。颜色列表回答“怎样安排”;上下界回答“目前知道最少需要多少到多少”;状态与原因回答“是否已经完成证明”;规范化输入与算法版本回答“这份结论对应哪道题”。DSATUR 提供有用的选择顺序,分支限界承担精确搜索,团和着色分别提供可检查的下界与上界,SQLite 则把这些信息完整留存。

这种设计的价值在预算耗尽时尤其明显:程序仍能交付一个合法方案,而且诚实保留未知部分。以后增加预算、改善初始上界或引入更强下界时,可以逐次缩小区间,而不需要推翻之前那份本来就没有充分证据的“最优”承诺。工程上的可信度,往往来自这些明确的边界,而不是算法名字听起来有多强。

参考资料

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