Python sqlite3 二分图检查:BFS 两色划分与可验证奇环证书
如果一张关系图要被分成两组,而且每条关系都必须跨组,连通性只能说明谁和谁能相遇,不能说明这样的分组是否存在。例如四边形可以交替染色,三角形却会在最后一条边上发生矛盾。本文用 Python 标准库 sqlite3 保存顶点与边,在 Python 中执行迭代广度优先搜索,最后交付可复查的两色划分或奇环证书。

全文九个代码块都是完整的独立脚本,可分别保存后运行,不需要复制前文定义,不依赖第三方包,也不修改磁盘数据库。代码下方是实际运行得到的标准输出。测试环境为 Python 3.12.14 与 SQLite 3.53.1;需要 Python 3.10 或更新版本,以及支持 STRICT 表的 SQLite 3.37.0 或更新版本。SQLite 版本取决于 Python 链接的库,不能只看 Python 版本号。
本文不求最大匹配、不自动修复坏边,也不把有向图直接套用为无向图。业务若有方向语义,必须先明确是否允许忽略方向。目标始终是一个可以检查的判断:成功时每个顶点都有明确归属,失败时指出一条真实存在的奇数长度环。
1. 把顶点全集与无向邻接关系分开
先约定输入语义:顶点由整数编号标识,边没有方向,也没有权重。顶点表是完整名册,边表只记录关系,因此没有任何边的顶点也必须出现在顶点表里。本文允许原始边重复、反向重复和自环;重复只影响存储行数,自环则保留为真正的约束。读取时用 UNION 合并两个方向,得到去重后的邻接关系,不把重复出现的同一条边当成新的限制。
这里故意不加 u 小于 v 的约束,因为数据入口可能来自不同系统。外键负责拒绝引用不存在顶点的边,STRICT 表提供存储类型约束,不能替代业务层对编号范围和来源的检查。外键开关在事务外设置并核验,符合 SQLite 外键文档的使用要求。所有值通过占位符绑定;连接由 closing 关闭,事务由 with db 提交或回滚,这两件事不是同一件事。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
vertices = [1, 2, 3, 4, 9]
edges = [(1, 2), (2, 1), (1, 2), (2, 3), (3, 4), (4, 1)]
adj = load_graph(vertices, edges)
print(sorted(adj.items()))
print("raw_rows:", len(edges))
print("adjacency_rows:", sum(map(len, adj.values())))运行结果:
[(1, [2, 4]), (2, [1, 3]), (3, [2, 4]), (4, [1, 3]), (9, [])] raw_rows: 6 adjacency_rows: 8
无向四边形最终有八条有向邻接记录,原始数据有六行,这两个数量回答不同问题。顶点 9 的空列表同样是有效输入。读取顶点和边放在一个显式读事务内;换成文件数据库时也应保持这个边界,避免把两个时刻的数据拼接为一张图。这里一次读入内存,后面的 BFS 不再逐个顶点发 SQL 查询。
2. 先完成跨分量的两色划分
二分图要求每条边的两个端点颜色不同,颜色只有 0 和 1。选一个尚未染色的顶点作为根,把它设为 0;沿边发现新顶点时赋相反颜色。队列取出一个顶点后检查它的全部邻居。如果已染色邻居与当前点同色,判定失败。外层循环不能省略,否则第一块连通区域成功,可能掩盖另一块区域中的三角形。
发现顶点时立即染色,再放入队列,才能保证每个顶点最多入队一次。队列使用 deque 的 append 与 popleft;Python 文档说明两端操作具有近似常数时间性能。不要使用带 maxlen 的队列,因为容量满后丢弃旧元素会悄悄破坏搜索完整性。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def two_color(adj):
color = {}
for root in sorted(adj):
if root in color:
continue
color[root] = 0
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v] = 1 - color[u]
queue.append(v)
elif color[v] == color[u]:
return None
return color
adj = load_graph([1, 2, 3, 4, 10, 11, 99],
[(1, 2), (2, 3), (3, 4), (4, 1), (10, 11)])
color = two_color(adj)
assert color is not None
print("left:", sorted(v for v in color if color[v] == 0))
print("right:", sorted(v for v in color if color[v] == 1))
print("all_edges_cross:", all(color[u] != color[v]
for u in adj for v in adj[u]))运行结果:
left: [1, 3, 10, 99] right: [2, 4, 11] all_edges_cross: True
左右两组不要求人数相等,孤立点可以放在任意一组。本文把每个分量的最小编号顶点固定为颜色 0,因此孤立点也归入左组。这只是可重复的输出约定,不代表业务上天然存在左右身份。对于不连通图,每个分量都能独立交换两种颜色;不要把另一个实现给出的合法相反配色误判为错误。
3. 把同色冲突还原成一条奇环
只返回 False 对排查数据不够友好。我们为首次发现的每个顶点保存 parent,形成一片 BFS 树。当边 u 到 v 的两端同色时,沿 u 的父链上溯并记录位置,再沿 v 的父链上溯,直到遇到共同祖先。拼接 u 到共同祖先、共同祖先到 v,再补上冲突边回到 u,就得到闭合路径。共同祖先只出现一次,避免把共享树干来回走两遍。
为什么边数一定是奇数?树上每走一条父边颜色翻转一次,所以同色端点到共同祖先的距离同奇偶。两段树路长度相加为偶数,再加冲突边就是奇数。树路径在共同祖先以前不相交,所以除了首尾相同,中间顶点不重复。自环使 u 与 v 相等,算法自然返回两个相同编号,代表一条长度为一的环。Princeton Algorithms 的二分图接口说明也以两色划分或奇环作为两种结果。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
adj = load_graph([0, 1, 2, 3, 4, 8],
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)])
color, cycle = analyze(adj)
print("bipartite:", color is not None)
print("odd_cycle:", cycle)
print("edge_count:", len(cycle) - 1)运行结果:
bipartite: False odd_cycle: [2, 1, 0, 4, 3, 2] edge_count: 5
失败时返回 None 和奇环,而不返回已经染了一半的 color,防止调用方把局部结果当成完整分组。成功时返回完整颜色字典和空列表。该接口给出一条足以证明失败的奇环,不承诺全图最短奇环,也不承诺枚举所有冲突。BFS 的最短路径性质不能直接变成这里的全局最短奇环保证。
4. 让边界情况成为可执行回归用例
空图与只有孤立点的图都满足二分条件,因为不存在违反约束的边。重复边不应改变答案;反向重复也一样。自环不能被过滤掉,否则本来不满足条件的数据会被误报为成功。把这些情况放在同一个用例表里,比在业务代码里四处补特殊分支更容易维护。最后一个用例特意把坏分量放在正常分量之后,用来抓住只从第一个根搜索的实现缺陷。
每个用例都重新创建内存数据库,避免上一次测试遗留的表、颜色或父指针影响结果。预期值同时约束成功与失败分支。若你的业务禁止自环,应在导入时明确拒绝并记录原因;不要在判定函数里默默删除证据。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
cases = [
("empty", [], [], True),
("isolated", [7], [], True),
("duplicates", [1, 2], [(1, 2), (2, 1), (1, 2)], True),
("self_loop", [4], [(4, 4)], False),
("late_triangle", [1, 2, 7, 8, 9],
[(1, 2), (7, 8), (8, 9), (9, 7)], False),
]
for name, vertices, edges, expected in cases:
color, cycle = analyze(load_graph(vertices, edges))
actual = color is not None
assert actual == expected
print(name, actual, cycle)运行结果:
empty True [] isolated True [] duplicates True [] self_loop False [4, 4] late_triangle False [8, 7, 9, 8]
这里的空字典是成功结果,不能用 if color 判断是否成功:空字典的真假值为假,却不是 None。相同道理,孤立顶点的零颜色也是合法值,检查是否访问过应使用成员测试,而不是检查颜色是否为真。这类接口细节比三角形演示更容易在实际代码中造成错误。
5. 用独立验证器检查正反两类证书
算法结果不能只靠自己相信自己。正证书是完整颜色映射:键集合必须恰好等于顶点全集,颜色必须为整数 0 或 1,原始每条边的端点必须异色。负证书是闭合奇环:至少有一条边、首尾相同、边数为奇数、内部顶点无重复,且相邻编号确实在原始边表中相连。验证器从原始 vertices 与 edges 计算边集合,不使用 BFS 的 parent,也不复用邻接查询。
验证器把所有条件写成布尔结果,适合接收已经解码为整数列表与字典的内部数据;它不是面向任意不可信对象的通用解析器。若证书来自外部 JSON,还应先校验字段类型、长度和编号范围。下面有意提交一条不存在的边、一条偶环、一个漏掉孤立点的配色,以及伪造的一边环,确认验证器真的会拒绝错误结果。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
def verify(vertices, edges, color, cycle):
nodes = set(vertices)
pairs = {tuple(sorted((u, v))) for u, v in edges}
if color is not None:
return (not cycle and set(color) == nodes
and all(type(c) is int and c in (0, 1)
for c in color.values())
and all(u in color and v in color
and color[u] != color[v] for u, v in pairs))
if len(cycle) < 2 or cycle[0] != cycle[-1]:
return False
interior = cycle[:-1]
return ((len(cycle) - 1) % 2 == 1
and len(set(interior)) == len(interior)
and set(interior) <= nodes
and all(tuple(sorted((u, v))) in pairs
for u, v in zip(cycle, cycle[1:])))
vertices = [0, 1, 2, 3, 4, 99]
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
color, cycle = analyze(load_graph(vertices, edges))
print("generated:", verify(vertices, edges, color, cycle))
print("missing_edge:", verify(vertices, edges, None, [0, 1, 3, 0]))
print("even_walk:", verify(vertices, edges, None, [0, 1, 0]))
print("fake_loop:", verify(vertices, edges, None, [99, 99]))
print("missing_vertex:", verify([1, 2, 9], [(1, 2)], {1: 0, 2: 1}, []))
print("valid_color:", verify([1, 2, 9], [(1, 2)], {1: 0, 2: 1, 9: 0}, []))运行结果:
generated: True missing_edge: False even_walk: False fake_loop: False missing_vertex: False valid_color: True
奇环证书无需覆盖全图。只要其中一小部分真实关系已经无法两色划分,就足够否定整张图。正证书则必须覆盖所有顶点并检查所有边,这种不对称决定了两类验证器的形状。测试不能只断言环的长度为奇数,因为随便编三个编号也能通过那个过弱的条件。
6. 让输入顺序变化不再制造结果噪声
可重复性需要控制三个地方:根顶点顺序、每个邻居列表的顺序,以及环的表示方式。前两项由排序后的顶点与 SQL ORDER BY 保证。SQLite SELECT 文档明确说明,没有 ORDER BY 时返回顺序未定义。即使在当前数据量上恰好稳定,也不能依赖插入顺序、索引扫描顺序或 UNION 的内部去重顺序。
第三项是展示规范:同一个环可以从任意顶点开始,也可以顺时针或逆时针写出。下面把最小编号旋转到开头,再在两个方向中选择字典序较小的表示。因为已经验证内部顶点唯一,最小编号位置也唯一;不需要生成所有旋转组合。注意,这只是规范化已找到的环,不会替你从全图所有奇环里挑一个全局最优答案。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
def canonical(cycle):
ring = cycle[:-1]
i = ring.index(min(ring))
forward = ring[i:] + ring[:i]
reverse = [forward[0]] + forward[:0:-1]
result = min(forward, reverse)
return result + [result[0]]
vertices = [0, 1, 2, 3, 4, 9]
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
variants = [edges, list(reversed(edges)),
[(v, u) for u, v in edges] + edges + edges]
results = [analyze(load_graph(list(reversed(vertices)), rows))[1]
for rows in variants]
print("same_witness:", all(x == results[0] for x in results))
print("canonical:", canonical(results[0]))
print("reversed_equal:", canonical(results[0]) == canonical(results[0][::-1]))运行结果:
same_witness: True canonical: [0, 1, 2, 3, 4, 0] reversed_equal: True
这个约定固定的是同一编号图的输出。若业务重新分配顶点编号,颜色朝向和选中的冲突都可能改变,虽然二分性不变。断言结果时应区分语义正确、同图重复执行稳定、不同编号之间同构等价,不能把这三个要求混成一个字符串比较。
7. 把成功分组交给 SQL 再验一遍
前面的证书检查在 Python 中完成,这次把正证书装入临时分组表,让 SQLite 对原始边做复核。主键保证一个顶点只有一条分组记录,CHECK 约束颜色域,再分别检查缺失顶点、额外顶点与同色边。只比较记录总数是不够的:少一个正确编号、多一个陌生编号时,总数仍然相同。
示例是独立的内存数据库,图数据在计算与复核之间不会变化。真实文件数据库若有并发写入,应把证书绑定到明确的图版本,或在同一一致性边界内读取和验证。SQLite 隔离性说明提供读事务快照的依据,但一次计算结束后得到的证书不会自动追踪未来新增的边。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
vertices = [1, 2, 3, 4, 9]
edges = [(1, 2), (2, 3), (3, 4), (4, 1), (2, 1)]
color, cycle = analyze(load_graph(vertices, edges))
assert color is not None and not cycle
with closing(sqlite3.connect(":memory:")) as db:
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(u INTEGER NOT NULL, v INTEGER NOT NULL) STRICT;
CREATE TABLE partition(
id INTEGER PRIMARY KEY,
side INTEGER NOT NULL CHECK(side IN (0, 1))
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)", ((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.executemany("INSERT INTO partition VALUES (?, ?)", sorted(color.items()))
missing = db.execute("""
SELECT id FROM vertex EXCEPT SELECT id FROM partition
""").fetchall()
extra = db.execute("""
SELECT id FROM partition EXCEPT SELECT id FROM vertex
""").fetchall()
bad = db.execute("""
SELECT DISTINCT e.u, e.v FROM edge AS e
JOIN partition AS a ON a.id = e.u
JOIN partition AS b ON b.id = e.v
WHERE a.side = b.side ORDER BY e.u, e.v
""").fetchall()
print("missing:", missing)
print("extra:", extra)
print("same_color_edges:", bad)
print("sql_verified:", not missing and not extra and not bad)运行结果:
missing: [] extra: [] same_color_edges: [] sql_verified: True
这段 SQL 复核假定原始边的端点已经通过第一步的外键检查;若拿来检查任意外部边表,还要补充端点不存在的检查,避免内连接静默排除坏行。两个空集合与零条同色边共同构成成功条件。将来写入持久化结果时,建议同时保存图版本、算法版本与生成时间,而不是只保留一列颜色。
8. 穷举小图,用完全不同的方法做裁判
回归样例适合解释问题,穷举更适合寻找遗漏。对于至多四个顶点,列出包含自环在内的全部可能无向边,再枚举每条边是否存在。独立裁判不执行 BFS,也不维护父指针,而是枚举所有二进制配色,寻找是否存在让每条边异色的方案。算法结构越不同,共享同一错误的机会越小。
每张图都经过 SQLite 装载与主算法,再与暴力答案比较;无论成功失败,都继续验证输出证书。顶点数为四时有十个候选边位,共有一千零二十四张图;加上零到三个顶点的情况,总数是一千零九十九。这里没有随机种子、网络依赖或第三方图论包,输出可稳定复现。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
def verify(vertices, edges, color, cycle):
nodes = set(vertices)
pairs = {tuple(sorted((u, v))) for u, v in edges}
if color is not None:
return (not cycle and set(color) == nodes
and all(type(c) is int and c in (0, 1)
for c in color.values())
and all(u in color and v in color
and color[u] != color[v] for u, v in pairs))
if len(cycle) < 2 or cycle[0] != cycle[-1]:
return False
interior = cycle[:-1]
return ((len(cycle) - 1) % 2 == 1
and len(set(interior)) == len(interior)
and set(interior) <= nodes
and all(tuple(sorted((u, v))) in pairs
for u, v in zip(cycle, cycle[1:])))
from itertools import combinations_with_replacement, product
def oracle(vertices, edges):
for bits in product((0, 1), repeat=len(vertices)):
color = dict(zip(vertices, bits))
if all(color[u] != color[v] for u, v in edges):
return True
return False
checked = 0
for n in range(5):
vertices = list(range(n))
candidates = list(combinations_with_replacement(vertices, 2))
for mask in range(1 << len(candidates)):
edges = [edge for i, edge in enumerate(candidates) if mask & (1 << i)]
color, cycle = analyze(load_graph(vertices, edges))
assert (color is not None) == oracle(vertices, edges)
assert verify(vertices, edges, color, cycle)
checked += 1
print("graphs_checked:", checked)
print("oracle_and_certificates: passed")运行结果:
graphs_checked: 1099 oracle_and_certificates: passed
穷举裁判的指数成本是有意接受的,因为它只服务于小规模测试,不能替换生产算法。此处检查范围仍然有限:五环最小需要五个顶点,已经由第三个示例单独覆盖;长链与资源约束则留给下一节。测试矩阵应同时有小图穷举、精心设计的结构和接近运行边界的数据。
9. 长链测试与预算失败要分清含义
迭代搜索不占用与路径长度成比例的 Python 递归调用栈,因此适合检查长链。下面使用三千个顶点的链,要求得到完整的两色划分。随后故意收紧顶点预算,确认程序明确拒绝装载。超预算、数据库异常与发现奇环是三种不同结论,不能都压缩成 False,否则调用方无法判断是数据确实不满足约束,还是程序根本没有完成检查。
预算统计原始边行数,因为大量重复行也会带来读取和去重成本。这个示例的限制只保护邻接表装载阶段;它不限制此前构造测试数据库的成本,也不是 SQL 执行超时。真正接入已有数据库时,先在同一个读事务内统计并检查,再读取顶点与边;更大的数据还需要查询时间、临时存储和进程内存的独立限制。
import sqlite3
from collections import deque
from contextlib import closing
def load_graph(vertices, edges, max_vertices=10000, max_rows=20000):
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE vertex(id INTEGER PRIMARY KEY) STRICT;
CREATE TABLE edge(
u INTEGER NOT NULL REFERENCES vertex(id),
v INTEGER NOT NULL REFERENCES vertex(id)
) STRICT;
""")
with db:
db.executemany("INSERT INTO vertex VALUES (?)",
((v,) for v in vertices))
db.executemany("INSERT INTO edge VALUES (?, ?)", edges)
db.execute("BEGIN")
n = db.execute("SELECT count(*) FROM vertex").fetchone()[0]
m = db.execute("SELECT count(*) FROM edge").fetchone()[0]
if n > max_vertices or m > max_rows:
raise ValueError("graph exceeds load budget")
adj = {v: [] for (v,) in db.execute(
"SELECT id FROM vertex ORDER BY id")}
for u, v in db.execute("""
SELECT u, v FROM edge
UNION
SELECT v, u FROM edge
ORDER BY 1, 2
"""):
adj[u].append(v)
db.commit()
return adj
def odd_cycle(u, v, parent):
path, position = [], {}
x = u
while x is not None:
position[x] = len(path)
path.append(x)
x = parent[x]
branch = []
x = v
while x not in position:
branch.append(x)
x = parent[x]
return path[:position[x] + 1] + branch[::-1] + [u]
def analyze(adj):
color, parent = {}, {}
for root in sorted(adj):
if root in color:
continue
color[root], parent[root] = 0, None
queue = deque([root])
while queue:
u = queue.popleft()
for v in adj[u]:
if v not in color:
color[v], parent[v] = 1 - color[u], u
queue.append(v)
elif color[v] == color[u]:
return None, odd_cycle(u, v, parent)
return color, []
def verify(vertices, edges, color, cycle):
nodes = set(vertices)
pairs = {tuple(sorted((u, v))) for u, v in edges}
if color is not None:
return (not cycle and set(color) == nodes
and all(type(c) is int and c in (0, 1)
for c in color.values())
and all(u in color and v in color
and color[u] != color[v] for u, v in pairs))
if len(cycle) < 2 or cycle[0] != cycle[-1]:
return False
interior = cycle[:-1]
return ((len(cycle) - 1) % 2 == 1
and len(set(interior)) == len(interior)
and set(interior) <= nodes
and all(tuple(sorted((u, v))) in pairs
for u, v in zip(cycle, cycle[1:])))
vertices = list(range(3000))
edges = [(i, i + 1) for i in range(2999)]
color, cycle = analyze(load_graph(vertices, edges))
assert verify(vertices, edges, color, cycle)
print("vertices:", len(color))
print("left_right:", sum(c == 0 for c in color.values()),
sum(c == 1 for c in color.values()))
print("long_path_verified:", True)
try:
load_graph(vertices, edges, max_vertices=1000)
except ValueError as exc:
print("budget:", str(exc))运行结果:
vertices: 3000 left_right: 1500 1500 long_path_verified: True budget: graph exceeds load budget
在邻接表上,核心 BFS 访问每个顶点一次、每个邻接记录一次,时间为 O(V+E),额外的颜色、父指针与队列空间为 O(V)。实现中的根排序 sorted(adj) 对一般输入另有 O(V log V) 的最坏排序上界;本装载器已经按编号建立字典。首次冲突后的父链重建至多访问 O(V) 个顶点。装载阶段还包括 SQL 去重与排序成本,不能把整个数据库到结果的流程一概宣称为线性时间。邻接表本身占 O(V+E) 空间,Python 对象开销通常比两个整数的裸字节数大得多。
结语:让结论携带证据
可靠的二分图检查可以分为三个独立层次:数据库层给出一致、完整、确定顺序的无向邻接关系;搜索层通过两色约束产出分组或冲突;验证层用原始顶点和边检查证书。三层各有失败方式,也应该有各自的测试。
落地时最值得保留的不是某个固定的环编号,而是这些契约:孤立点不丢失,自环不被悄悄清除,重复边不改变语义,所有分量都被覆盖,失败的半成品颜色不向外泄漏。再把成功配色和失败奇环交给独立检查器,结果就能被其他程序、人或审计流程重新确认。
官方资料与复核范围
Python sqlite3 文档:连接、参数绑定、事务与关闭连接。
SQLite STRICT Tables:STRICT 表支持版本与类型规则。
SQLite SELECT:UNION 去重与 ORDER BY。
SQLite Foreign Key Support:外键启用与事务边界。
Python collections.deque:队列两端操作。
Princeton Algorithms:Bipartite:二分性与奇环证书。
SQLite Isolation:一致性读取与并发边界。
资料于 2026 年 10 月 19 日核对。示例采用本文独立实现,暴力裁判和证书检查均随代码给出;可运行测试覆盖的是文中明确列出的输入范围,并不替代业务数据验证或生产环境容量评估。

