Python sqlite3 最大流与最小割:保留残量边身份的 Edmonds–Karp 实战

10-19 4阅读

一张运输网络里,线路各有上限,但真正限制总吞吐量的可能是几条看似不起眼的连接。本文用 Python 标准库 sqlite3 保存有向多重图,在内存中实现 Edmonds–Karp 最大流,再把最小割变成可以独立核验的最优性证书。重点不只是算出一个数,而是让每条业务边的流量有身份、每次撤回有依据、最终答案有上界证明。

Python sqlite3 最大流与最小割:保留残量边身份的 Edmonds–Karp 实战
AI 生成的概念配图:并行通道、容量瓶颈与数据存储意象,不对应正文某一张精确图。

运行条件:Python 3.12 或更新版本,使用标准库,无需安装图算法包。本文在 Python 3.12.14、SQLite 3.53.1 上以 python -X dev -W error 逐段测试,九段示例分别在新进程中运行,输出逐字核对。官方接口说明以文末链接为准;算法实现、数据与对照测试均为本文独立编写。

一、把容量合同落实到数据库入口

最大流处理的是一张带容量的有向网络。每条边有自己的编号、起点、终点和非负容量;同一对端点可以有多条边,反方向也可以另有一条真实边。源点负责提供流量,汇点负责接收流量,其余点不能凭空制造或吞掉流量。本文以整数单位建模,例如每分钟可通过的整批货物,不讨论费用、下界、多个商品相互竞争或浮点近似。源点和汇点必须存在且不同,孤立点保留在顶点表中,自环允许存在,但不会提高源汇之间的最大流。

边的身份不能由起终点二元组代替,因此表上不建立端点唯一约束。容量使用 SQLite 能存储的非负有符号六十四位整数。需要注意,INTEGER 是类型亲和性,数据库可能把数值文本转成整数;CHECK 检查的是存储后的类型,并不能证明调用方传来的对象原本就是整数。若接口合同要求拒绝布尔值、字符串与浮点数,应当在 Python 入库前再做一次精确类型检查。下面同时演示入口检查与数据库兜底,所有数据值都通过占位符绑定。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise
def insert_edge(db, edge):
    capacity = edge[3]
    if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
        raise ValueError("capacity must be a nonnegative int64")
    db.execute("INSERT INTO edge VALUES(?, ?, ?, ?)", edge)

with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "t"], [])
    for bad in [-1, 1.5, True, "2", 2**63]:
        try:
            insert_edge(db, (1, "s", "t", bad))
        except ValueError:
            print("rejected", repr(bad))
    insert_edge(db, (1, "s", "t", 3))
    insert_edge(db, (2, "s", "t", 0))
    try:
        db.execute("INSERT INTO edge VALUES(3, 's', 'missing', 1)")
    except sqlite3.IntegrityError:
        print("foreign key rejected")
    try:
        db.execute("INSERT INTO edge VALUES(4, 's', 't', 0.5)")
    except sqlite3.IntegrityError:
        print("stored real rejected")
    print(db.execute("SELECT id, capacity FROM edge ORDER BY id").fetchall())

准确输出:

rejected -1
rejected 1.5
rejected True
rejected '2'
rejected 9223372036854775808
foreign key rejected
stored real rejected
[(1, 3), (2, 0)]

这里特意用 closing 明确关闭连接。SQLite 连接自己的上下文管理器主要处理事务,并不等价于关闭连接。全文九个代码块都能分别保存为独立脚本运行,无需先执行前一节;重复出现的辅助函数是为了让复制后的程序仍然完整。示例统一显式设置 isolation_level=None,再由需要一致性快照的函数执行 BEGIN 与 COMMIT。

二、残量弧必须保留原始边编号

一条容量为五、当前流量为三的原始边,带来两种后续选择:顺着原方向还可增加二,沿反方向可以撤回三。这两种选择属于同一条原始边,不能把撤回通道误认为图中本来存在的反向业务边。尤其在平行边和反平行边并存时,用 residual[u, v] 保存一个数字,会丢失把流量写回具体边的依据。可以聚合容量求总值,但若业务还要逐边分配,就需要额外而正确的拆分过程。

本文直接为每条原始边分配两个残量弧槽位。第 i 条边的正向弧是 2i,撤回弧是 2i+1;任意槽位 k 的配对槽位都是 k ^ 1。这个索引只在本次载入的边列表中有效,对外保存的身份始终是数据库的边编号和方向。下面不用算法,先用 SQL 展示两条平行边和一条反向边各自的残量弧。UNION ALL 保留重复端点,方向字段明确说明是增加还是撤回。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["a", "b"], [(10, "a", "b", 5),
                           (11, "a", "b", 2), (12, "b", "a", 4)])
    db.execute("CREATE TABLE allocation(edge_id INTEGER PRIMARY KEY, amount INTEGER)")
    db.executemany("INSERT INTO allocation VALUES(?, ?)", [(10, 3), (11, 1), (12, 2)])
    rows = db.execute("""
        SELECT e.id, 1 AS direction, src, dst, capacity - amount AS residual
        FROM edge AS e JOIN allocation AS a ON a.edge_id = e.id
        UNION ALL
        SELECT e.id, -1, dst, src, amount
        FROM edge AS e JOIN allocation AS a ON a.edge_id = e.id
        ORDER BY 1, 2 DESC
    """).fetchall()
    for row in rows:
        print(row)

准确输出:

(10, 1, 'a', 'b', 2)
(10, -1, 'b', 'a', 3)
(11, 1, 'a', 'b', 1)
(11, -1, 'b', 'a', 1)
(12, 1, 'b', 'a', 2)
(12, -1, 'a', 'b', 2)

这些给定流量只用于展示残量身份,不声称它们组成一个源汇可行流。注意,从 b 到 a 的残量弧既可能来自编号十的撤回,也可能来自编号十二的正向剩余额度。它们虽然方向相同,更新时却必须落到不同的原始边;下一节的父指针因此记录弧槽位,而不是只记录父顶点。

三、广度优先搜索找的是最少弧数增广路

Edmonds–Karp 每轮在正残量弧上做一次广度优先搜索,找到从源点到汇点弧数最少的路径。这里的最短不是容量总和最小,也不是按边权寻找代价最低的路线。队列用 deque,顶点首次被发现时写入父弧,源点一开始就标记为已访问。这样自环与回到源点的弧不会形成回溯循环,平行弧也不会重复把同一个顶点塞入队列。

找到路径后,从汇点逆着父弧回走,取路径上残量的最小值作为本轮增加量。下面只展示第一轮搜索,所以还不是完整最大流求解器。边按照编号载入、邻接表按照载入顺序追加,使多个同长度候选路径之间的选择可重复。不同的合法顺序可能产生不同逐边流量,但最终最大流值应相同。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "a", "b", "t"], [(1, "s", "a", 4),
         (2, "s", "b", 2), (3, "a", "t", 3), (4, "b", "t", 2)])
    vertices, edges = snapshot(db)
    adj, arcs = {v: [] for v in vertices}, []
    for _, u, v, c in edges:
        k = len(arcs)
        arcs.extend([[u, v, c], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    parent, queue = {"s": None}, deque(["s"])
    while queue and "t" not in parent:
        u = queue.popleft()
        for k in adj[u]:
            _, v, r = arcs[k]
            if r > 0 and v not in parent:
                parent[v] = k
                queue.append(v)
                if v == "t":
                    break
    path, v = [], "t"
    while v != "s":
        k = parent[v]
        path.append(k)
        v = arcs[k][0]
    path.reverse()
    print("edge ids:", [edges[k // 2][0] for k in path])
    print("bottleneck:", min(arcs[k][2] for k in path))

准确输出:

edge ids: [1, 3]
bottleneck: 3

一次增广必须同时减少所选弧的残量、增加配对弧的残量。两者之和始终等于这一条原始边的容量,因此恢复逐边流量时可直接计算容量减去正向残量。只改正向弧看似还能继续走路,却失去了撤回既有分配的能力,容易过早报告一个过小的答案。

四、完整求解器:从零流开始,直到汇点不可达

下面把建图、广度搜索、增广和结果恢复放到同一个函数中。每次调用都从零流开始,没有接受旧流量热启动的隐含行为。残量弧存放起点、终点和当前残量,原始边的容量不被修改。record 默认关闭,只有需要教学追踪时才保留每轮路径,避免把长增广历史永久堆在内存中。

当搜索失败时,最后一次广度搜索已经访问了源点可经正残量弧到达的全部顶点。这些顶点构成割的源侧集合。函数随后返回最大流值、按原始边编号组织的流量、源侧集合和可选追踪。紧接着调用的 certify 不重跑增广,而是直接检查每条边的容量限制、每个顶点的净流量,以及割容量是否等于流值。验算器以已由数据库验证的图为输入,用不同路径核对求解结果。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def maximum_flow(vertices, edges, source, sink, record=False):
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("invalid terminals")
    adj = {v: [] for v in vertices}
    arcs, ids = [], set()
    for edge_id, u, v, capacity in edges:
        if edge_id in ids or u not in adj or v not in adj:
            raise ValueError("invalid edge identity or endpoint")
        if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
            raise ValueError("invalid capacity")
        ids.add(edge_id)
        k = len(arcs)
        arcs.extend([[u, v, capacity], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    value, steps = 0, []
    while True:
        parent, queue = {source: None}, deque([source])
        while queue and sink not in parent:
            u = queue.popleft()
            for k in adj[u]:
                _, v, residual = arcs[k]
                if residual > 0 and v not in parent:
                    parent[v] = k
                    queue.append(v)
                    if v == sink:
                        break
        if sink not in parent:
            flows = {edge[0]: edge[3] - arcs[2 * i][2]
                     for i, edge in enumerate(edges)}
            return value, flows, set(parent), steps
        path, v = [], sink
        while v != source:
            k = parent[v]
            path.append(k)
            v = arcs[k][0]
        amount = min(arcs[k][2] for k in path)
        for k in path:
            arcs[k][2] -= amount
            arcs[k ^ 1][2] += amount
        value += amount
        if record:
            route = [(edges[k // 2][0], -1 if k % 2 else 1)
                     for k in reversed(path)]
            steps.append((amount, route))

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "a", "b", "t", "isolated"], [
        (1, "s", "a", 3), (2, "s", "a", 2), (3, "a", "s", 1),
        (4, "s", "b", 2), (5, "a", "b", 2), (6, "a", "t", 3),
        (7, "b", "t", 4), (8, "b", "b", 99)])
    vertices, edges = snapshot(db)
    value, flows, side, _ = maximum_flow(vertices, edges, "s", "t")
    cut = certify(vertices, edges, "s", "t", value, flows, side)
    print("maximum:", value)
    print("flows:", sorted(flows.items()))
    print("source side:", sorted(side))
    print("cut:", cut)

准确输出:

maximum: 7
flows: [(1, 3), (2, 2), (3, 0), (4, 2), (5, 2), (6, 3), (7, 4), (8, 0)]
source side: ['s']
cut: 7

这里源点有入边,汇点也可以有出边,因此通用验算不能只把源点所有出边相加就当作流值。应比较源点的净流出与汇点的净流入;中间顶点净值为零。自环在同一顶点一减一加,自动抵消。整数运算使容量检查与证书等式都可以精确比较,不需要为误差选择容差。

五、让反向残量弧真的参与一次改道

只用互不干扰的平行线路做测试,很容易让缺少撤回逻辑的错误实现蒙混过关。下面构造两条最终可同时使用的路线,但第一轮按编号顺序会选择穿过 a 到 c 的路线。第一轮结束后,第二次必须经过 c 到 a 的残量撤回弧,把原来占用 a 到 c 的一个单位取消,再转向 d 到汇点。

日志中的每个二元组是原始边编号和方向:正一表示增加这条业务边的流量,负一表示撤回。方向只是残量遍历动作,不是最终允许业务边存储负流量。这个例子最后编号三的边流量回到零,其他需要的边各运送一个单位。它比只验证结果等于二更强,因为还明确证明了撤回通道实际被执行。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def maximum_flow(vertices, edges, source, sink, record=False):
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("invalid terminals")
    adj = {v: [] for v in vertices}
    arcs, ids = [], set()
    for edge_id, u, v, capacity in edges:
        if edge_id in ids or u not in adj or v not in adj:
            raise ValueError("invalid edge identity or endpoint")
        if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
            raise ValueError("invalid capacity")
        ids.add(edge_id)
        k = len(arcs)
        arcs.extend([[u, v, capacity], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    value, steps = 0, []
    while True:
        parent, queue = {source: None}, deque([source])
        while queue and sink not in parent:
            u = queue.popleft()
            for k in adj[u]:
                _, v, residual = arcs[k]
                if residual > 0 and v not in parent:
                    parent[v] = k
                    queue.append(v)
                    if v == sink:
                        break
        if sink not in parent:
            flows = {edge[0]: edge[3] - arcs[2 * i][2]
                     for i, edge in enumerate(edges)}
            return value, flows, set(parent), steps
        path, v = [], sink
        while v != source:
            k = parent[v]
            path.append(k)
            v = arcs[k][0]
        amount = min(arcs[k][2] for k in path)
        for k in path:
            arcs[k][2] -= amount
            arcs[k ^ 1][2] += amount
        value += amount
        if record:
            route = [(edges[k // 2][0], -1 if k % 2 else 1)
                     for k in reversed(path)]
            steps.append((amount, route))

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "a", "b", "c", "d", "t"], [
        (1, "s", "a", 1), (2, "s", "b", 1), (3, "a", "c", 1),
        (4, "a", "d", 1), (5, "b", "c", 1), (6, "c", "t", 1),
        (7, "d", "t", 1)])
    vertices, edges = snapshot(db)
    value, flows, side, steps = maximum_flow(vertices, edges, "s", "t", record=True)
    certify(vertices, edges, "s", "t", value, flows, side)
    for number, (amount, route) in enumerate(steps, 1):
        print("step", number, "amount", amount, "route", route)
    assert any(direction == -1 for _, route in steps for _, direction in route)
    assert flows[3] == 0
    print("maximum:", value)
    print("flows:", sorted(flows.items()))

准确输出:

step 1 amount 1 route [(1, 1), (3, 1), (6, 1)]
step 2 amount 1 route [(2, 1), (5, 1), (3, -1), (4, 1), (7, 1)]
maximum: 2
flows: [(1, 1), (2, 1), (3, 0), (4, 1), (5, 1), (6, 1), (7, 1)]

增广路径不会重复顶点,因此同一轮不会同时绕一圈再返回某个节点;但不同轮可以重新利用先前出现过的边。不能把原图边永久标记为已用,也不能把某次搜索的 visited 保留到下一轮。每轮必须面对更新后的残量网络重新搜索。

六、用可行流与同值割组成独立证书

为什么一个流量分配表加一个顶点集合,就足以证明最优?先检查流量可行。对源侧所有顶点的净流量求和,内部边的贡献彼此抵消,只剩跨边界的净流出。任何可行流的值都不超过从源侧指向另一侧的边容量总和;反向跨入的边只会降低净流出,不能加到割容量里。如果某个可行流已经等于这个上界,就没有其他流能比它更大。

因此割证书不依赖增广历史,也不必采用求解器内部的残量表示。下面直接从数据库读取一张小图,手工提供正确答案,再分别破坏容量、守恒以及割等式。测试不依赖 assert 实现业务拒绝:验算失败使用 ValueError,外层捕获并打印具体原因。这里单独暴露证书检查,也方便将来把求解器换成另一种算法而保留同一套验收接口。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "a", "t"], [(1, "s", "a", 4), (2, "a", "t", 3)])
    vertices, edges = snapshot(db)
    print("valid cut:", certify(vertices, edges, "s", "t", 3,
                                 {1: 3, 2: 3}, {"s", "a"}))
    cases = [
        (3, {1: 5, 2: 3}, {"s", "a"}),
        (3, {1: 2, 2: 3}, {"s", "a"}),
        (2, {1: 2, 2: 2}, {"s", "a"}),
        (3, {1: 3, 2: 3}, {"s", "t"}),
    ]
    for value, flows, side in cases:
        try:
            certify(vertices, edges, "s", "t", value, flows, side)
        except ValueError as exc:
            print("rejected:", exc)

准确输出:

valid cut: 3
rejected: capacity
rejected: conservation
rejected: cut equality
rejected: cut partition

求解器停止时,源侧通向外侧的原始边必然饱和,否则其正向残量弧还可以把外侧顶点纳入可达集合;外侧进入源侧的原始边必然为零流,否则撤回弧同样会扩大集合。这解释了为何最后一次失败搜索给出的集合能达到流值上界。仅仅比较一个数字与某条路径的瓶颈,或者只检验中间点守恒,都不足以证明最优。

七、零容量、断路、自环与大整数总量

容量为零的边可以保留,它在初始残量搜索中不可通过。源汇不连通时,最大流为零,仍然有合法的零容量割证书。自环即使有很大容量也不产生源汇运输能力,因为搜索不会再次访问当前顶点。源点等于汇点则拒绝,避免把空路径误当成无限可增广路线。

另一个常见边界是每条边都能放进 SQLite INTEGER,但总流量已经超过其最大整数。Python 的整数求和可继续精确进行;SQLite 的整数 SUM 在结果溢出时会报错,改用浮点 TOTAL 又可能损失精度。本文因此将割容量与净流量累计放在 Python 中。若日后保存总值,应明确选用十进制文本等格式,不要未经检查绑定到 INTEGER 列。下面两条满容量平行边专门覆盖这个边界。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def maximum_flow(vertices, edges, source, sink, record=False):
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("invalid terminals")
    adj = {v: [] for v in vertices}
    arcs, ids = [], set()
    for edge_id, u, v, capacity in edges:
        if edge_id in ids or u not in adj or v not in adj:
            raise ValueError("invalid edge identity or endpoint")
        if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
            raise ValueError("invalid capacity")
        ids.add(edge_id)
        k = len(arcs)
        arcs.extend([[u, v, capacity], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    value, steps = 0, []
    while True:
        parent, queue = {source: None}, deque([source])
        while queue and sink not in parent:
            u = queue.popleft()
            for k in adj[u]:
                _, v, residual = arcs[k]
                if residual > 0 and v not in parent:
                    parent[v] = k
                    queue.append(v)
                    if v == sink:
                        break
        if sink not in parent:
            flows = {edge[0]: edge[3] - arcs[2 * i][2]
                     for i, edge in enumerate(edges)}
            return value, flows, set(parent), steps
        path, v = [], sink
        while v != source:
            k = parent[v]
            path.append(k)
            v = arcs[k][0]
        amount = min(arcs[k][2] for k in path)
        for k in path:
            arcs[k][2] -= amount
            arcs[k ^ 1][2] += amount
        value += amount
        if record:
            route = [(edges[k // 2][0], -1 if k % 2 else 1)
                     for k in reversed(path)]
            steps.append((amount, route))

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
cases = [
    ("disconnected", ["s", "a", "t"], [(1, "s", "a", 5)]),
    ("zero", ["s", "t"], [(1, "s", "t", 0)]),
    ("loops", ["s", "t"], [(1, "s", "s", 9), (2, "t", "t", 8)]),
    ("large", ["s", "t"], [(1, "s", "t", 2**63 - 1),
                               (2, "s", "t", 2**63 - 1)]),
]
for name, vertices, edges in cases:
    with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
        seed(db, vertices, edges)
        vertices, edges = snapshot(db)
        value, flows, side, _ = maximum_flow(vertices, edges, "s", "t")
        certify(vertices, edges, "s", "t", value, flows, side)
        print(name, value)
try:
    maximum_flow(["s"], [], "s", "s")
except ValueError as exc:
    print("rejected:", exc)

准确输出:

disconnected 0
zero 0
loops 0
large 18446744073709551614
rejected: invalid terminals

每条原始边的流量仍然不会超过自身容量,所以逐边结果可以安全地保持整数存储。不要把这个事实误推成总流量也一定能放入同一个字段。类似地,残量正反弧分别受一条原始边的配对不变量限制,不需要把两条反平行业务边的容量先相加。

八、先核验快照,再原子写入整批结果

内存算法针对的是一个确定版本的图。若一边读取顶点、一边读取边,其他连接恰好修改了数据,就可能混入两个版本。snapshot 用一个显式读事务包住两次查询,取得同一事务视图,再把数据物化到 Python。这个辅助函数要求调用方没有已开启的事务;它不是可以随意嵌套到任意事务中的通用组件。

如果计算后的结果必须与当前图共同提交,一个教学上简单的策略是从 BEGIN IMMEDIATE 开始,一直持有写事务直到结果通过证书检查并入库。下面故意在插入一条结果后触发外键失败,证明整批结果会回滚,然后再成功保存。实际系统要权衡计算期间占用写者的代价:大图更适合短事务读取带版本号的快照,在提交时检查版本未变化,不应把长时间计算无限塞进数据库写锁。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def maximum_flow(vertices, edges, source, sink, record=False):
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("invalid terminals")
    adj = {v: [] for v in vertices}
    arcs, ids = [], set()
    for edge_id, u, v, capacity in edges:
        if edge_id in ids or u not in adj or v not in adj:
            raise ValueError("invalid edge identity or endpoint")
        if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
            raise ValueError("invalid capacity")
        ids.add(edge_id)
        k = len(arcs)
        arcs.extend([[u, v, capacity], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    value, steps = 0, []
    while True:
        parent, queue = {source: None}, deque([source])
        while queue and sink not in parent:
            u = queue.popleft()
            for k in adj[u]:
                _, v, residual = arcs[k]
                if residual > 0 and v not in parent:
                    parent[v] = k
                    queue.append(v)
                    if v == sink:
                        break
        if sink not in parent:
            flows = {edge[0]: edge[3] - arcs[2 * i][2]
                     for i, edge in enumerate(edges)}
            return value, flows, set(parent), steps
        path, v = [], sink
        while v != source:
            k = parent[v]
            path.append(k)
            v = arcs[k][0]
        amount = min(arcs[k][2] for k in path)
        for k in path:
            arcs[k][2] -= amount
            arcs[k ^ 1][2] += amount
        value += amount
        if record:
            route = [(edges[k // 2][0], -1 if k % 2 else 1)
                     for k in reversed(path)]
            steps.append((amount, route))

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
    seed(db, ["s", "a", "t"], [(1, "s", "a", 4), (2, "a", "t", 3)])
    db.execute("""CREATE TABLE result(
        edge_id INTEGER PRIMARY KEY REFERENCES edge(id),
        amount INTEGER NOT NULL CHECK(typeof(amount) = 'integer' AND amount >= 0)
    )""")
    def save(fail=False):
        db.execute("BEGIN IMMEDIATE")
        try:
            vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
            edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
            value, flows, side, _ = maximum_flow(vertices, edges, "s", "t")
            certify(vertices, edges, "s", "t", value, flows, side)
            db.execute("DELETE FROM result")
            for index, (edge_id, amount) in enumerate(sorted(flows.items())):
                db.execute("INSERT INTO result VALUES(?, ?)", (edge_id, amount))
                if fail and index == 0:
                    db.execute("INSERT INTO result VALUES(999, 0)")
            db.execute("COMMIT")
            return value
        except BaseException:
            db.execute("ROLLBACK")
            raise
    try:
        save(fail=True)
    except sqlite3.IntegrityError:
        print("after rollback:", db.execute("SELECT COUNT(*) FROM result").fetchone()[0])
    print("saved maximum:", save())
    print(db.execute("SELECT edge_id, amount FROM result ORDER BY edge_id").fetchall())

准确输出:

after rollback: 0
saved maximum: 3
[(1, 3), (2, 3)]

结果表本身只检查非负整数和原始边存在,不能单靠一条普通 CHECK 表达跨表容量约束与全图守恒;因此求解与证书检查必须发生在提交之前。示例保存的是一次当前结果,没有承诺在未来修改容量后自动重新求解。生产环境应把图版本、源汇身份、运行编号和证书集合一并纳入结果设计,或在图更新时明确使旧结果失效。

九、用穷举割做小图全覆盖对照

最后的测试不把另一个增广算法当裁判,而是枚举所有包含源点、不包含汇点的顶点集合,直接计算每个割的容量,取最小值作为独立答案。对于 n 个顶点只有二的 n 减二次方个候选割,小图很适合这样做。这个裁判不用残量弧、不使用 BFS,也不会与求解器共享父指针或反向索引的错误。

覆盖分为四组:二点和三点完整有向边槽的容量取零到二;四点无自环的十二个有向槽取零或一;再用三点六个指定槽位,把平行边、反平行边与回到内部点的边放在同一模型中,容量也取零到二。零容量槽与不存在的边在流值和割容量上等价,但仍保留各自的边编号。每一组都经 SQLite 写入、按编号重新载入、求解、逐边验算,再与穷举割比较。

import sqlite3
from contextlib import closing
from collections import deque

SCHEMA = """
CREATE TABLE vertex(name TEXT PRIMARY KEY NOT NULL);
CREATE TABLE edge(
    id INTEGER PRIMARY KEY,
    src TEXT NOT NULL REFERENCES vertex(name),
    dst TEXT NOT NULL REFERENCES vertex(name),
    capacity INTEGER NOT NULL
        CHECK(typeof(capacity) = 'integer' AND capacity >= 0)
);
"""

def seed(db, vertices, edges):
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SCHEMA)
    db.executemany("INSERT INTO vertex VALUES(?)", [(v,) for v in vertices])
    db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", edges)

def snapshot(db):
    # This helper owns its transaction; the caller must have no open one.
    db.execute("BEGIN")
    try:
        vertices = [r[0] for r in db.execute("SELECT name FROM vertex ORDER BY name")]
        edges = db.execute("SELECT id, src, dst, capacity FROM edge ORDER BY id").fetchall()
        db.execute("COMMIT")
        return vertices, edges
    except BaseException:
        db.execute("ROLLBACK")
        raise

def maximum_flow(vertices, edges, source, sink, record=False):
    if len(set(vertices)) != len(vertices):
        raise ValueError("duplicate vertex")
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("invalid terminals")
    adj = {v: [] for v in vertices}
    arcs, ids = [], set()
    for edge_id, u, v, capacity in edges:
        if edge_id in ids or u not in adj or v not in adj:
            raise ValueError("invalid edge identity or endpoint")
        if type(capacity) is not int or not 0 <= capacity <= 2**63 - 1:
            raise ValueError("invalid capacity")
        ids.add(edge_id)
        k = len(arcs)
        arcs.extend([[u, v, capacity], [v, u, 0]])
        adj[u].append(k)
        adj[v].append(k + 1)
    value, steps = 0, []
    while True:
        parent, queue = {source: None}, deque([source])
        while queue and sink not in parent:
            u = queue.popleft()
            for k in adj[u]:
                _, v, residual = arcs[k]
                if residual > 0 and v not in parent:
                    parent[v] = k
                    queue.append(v)
                    if v == sink:
                        break
        if sink not in parent:
            flows = {edge[0]: edge[3] - arcs[2 * i][2]
                     for i, edge in enumerate(edges)}
            return value, flows, set(parent), steps
        path, v = [], sink
        while v != source:
            k = parent[v]
            path.append(k)
            v = arcs[k][0]
        amount = min(arcs[k][2] for k in path)
        for k in path:
            arcs[k][2] -= amount
            arcs[k ^ 1][2] += amount
        value += amount
        if record:
            route = [(edges[k // 2][0], -1 if k % 2 else 1)
                     for k in reversed(path)]
            steps.append((amount, route))

def certify(vertices, edges, source, sink, value, flows, side):
    if source == sink or source not in vertices or sink not in vertices:
        raise ValueError("terminals")
    if set(flows) != {e[0] for e in edges}:
        raise ValueError("edge set")
    if type(value) is not int or value < 0:
        raise ValueError("value")
    balance = dict.fromkeys(vertices, 0)
    for edge_id, u, v, capacity in edges:
        f = flows[edge_id]
        if type(f) is not int or not 0 <= f <= capacity:
            raise ValueError("capacity")
        balance[u] -= f
        balance[v] += f
    expected = dict.fromkeys(vertices, 0)
    expected[source], expected[sink] = -value, value
    if balance != expected:
        raise ValueError("conservation")
    if not side <= set(vertices) or source not in side or sink in side:
        raise ValueError("cut partition")
    cut = sum(c for _, u, v, c in edges if u in side and v not in side)
    if cut != value:
        raise ValueError("cut equality")
    return cut
from itertools import product

def exhaustive_cut(vertices, edges, source, sink):
    inner = [v for v in vertices if v not in (source, sink)]
    best = None
    for flags in product((False, True), repeat=len(inner)):
        side = {source} | {v for v, keep in zip(inner, flags) if keep}
        capacity = sum(c for _, u, v, c in edges if u in side and v not in side)
        best = capacity if best is None else min(best, capacity)
    return best

specs = []
for n, limit in [(2, 3), (3, 3), (4, 2)]:
    vertices = [str(i) for i in range(n)]
    slots = [(u, v) for u in vertices for v in vertices if u != v]
    specs.append((vertices, slots, limit))
specs.append((["0", "1", "2"], [("0", "1"), ("0", "1"),
    ("1", "0"), ("1", "2"), ("0", "2"), ("2", "1")], 3))
checked = 0
for vertices, slots, limit in specs:
    with closing(sqlite3.connect(":memory:", isolation_level=None)) as db:
        seed(db, vertices, [])
        for capacities in product(range(limit), repeat=len(slots)):
            db.execute("DELETE FROM edge")
            rows = [(i, u, v, c) for i, ((u, v), c)
                    in enumerate(zip(slots, capacities), 1)]
            db.executemany("INSERT INTO edge VALUES(?, ?, ?, ?)", rows)
            actual_vertices, edges = snapshot(db)
            source, sink = vertices[0], vertices[-1]
            value, flows, side, _ = maximum_flow(actual_vertices, edges, source, sink)
            certify(actual_vertices, edges, source, sink, value, flows, side)
            assert value == exhaustive_cut(actual_vertices, edges, source, sink)
            checked += 1
print("exhaustive graphs:", checked)
print("all certificates and cut oracles passed")

准确输出:

exhaustive graphs: 5563
all certificates and cut oracles passed

总共五千五百六十三张带容量网络全部通过,不等于已经证明任意规模实现都绝无错误;它的价值是给反平行、断路、零容量、方向与编号等细节提供系统性回归保护。前面的定向改道测试专门补充了六个顶点的撤回场景,大整数与自环由边界测试覆盖。测试范围应明确列出,不能用大量随机次数掩盖没有覆盖的输入类别。

实现边界与复杂度

把数据库边一次读入邻接结构后,正常求解状态占用 O(V+E) 空间;开启路径追踪还要加上保存历史的空间。Edmonds–Karp 的经典增广阶段上界为 O(VE²),容量很大并不意味着必须逐单位增广,每轮实际增加整条路径的瓶颈量。顶点、边的有序读取还涉及数据库查询及排序成本,不能把算法上界直接当成完整程序的墙钟时间保证。Python 大整数运算的位成本也没有包含在常见单位运算模型里。

如果应用只要求是否存在路线,或者寻找一条总代价最小的路径,最大流不是同一个问题。本文关心多条路线共同贡献的可实现吞吐量,以及哪个有向割给出了准确上限。若容量带小数,先确定业务单位并精确缩放为整数;若需要最小费用、边下界、多源多汇或持续增量更新,应另行扩展模型和证书,不能只改一个比较符号就宣称支持。

官方资料与核验入口

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