Yen无环路径排行实战:新路线已经选出,为什么旧候选堆不能清空
找到一条最短路以后,若还想要第二、第三条路线,不能简单地删掉整条已选路线。不同答案可以共享许多边;真正需要排除的是已经输出的完整顶点序列,同时保住各条路线内部不重复经过顶点。
Yen把新路线拆成固定根前缀和从分叉点出发的新尾段,再把各处分叉产生的候选放到同一个长期保留的最小堆。本篇重点是这些偏离约束与候选池;Dijkstra只负责在给定限制下求一条尾段。
AI模型生成的概念插图:一条分支路线旁保留多枚等待比较的路线模型,表达跨轮候选池;不对应正文精确图结构、边权或真实道路。
完整程序与实际输出
将下列完整程序保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码0、标准错误为空;只使用标准库与本地教学数据。
from heapq import heappop, heappush
from random import Random
def prepare(n, edges, source, target, k):
if (type(n) is not int or not 1 <= n <= 16
or type(k) is not int or not 0 <= k <= 64
or type(source) is not int or not 0 <= source < n
or type(target) is not int or not 0 <= target < n
or type(edges) not in (list, tuple) or len(edges) > n * (n - 1)):
raise ValueError("bounded graph, endpoints and K required")
graph = [dict() for _ in range(n)]
for edge in edges:
if type(edge) is not tuple or len(edge) != 3:
raise ValueError("edge must be a triple")
u, v, weight = edge
if (any(type(x) is not int for x in edge) or not 0 <= u < n
or not 0 <= v < n or u == v or not 0 <= weight <= 10 ** 6
or v in graph[u]):
raise ValueError("distinct directed edges and nonnegative integer weights required")
graph[u][v] = weight
return graph
def shortest(graph, source, target, blocked_nodes, blocked_edges):
if source in blocked_nodes or target in blocked_nodes:
return None
distance, parent, settled = {source: 0}, {}, set()
heap = [(0, source)]
while heap:
cost, u = heappop(heap)
if u in settled or cost != distance[u]:
continue
settled.add(u)
if u == target:
path = [u]
while path[-1] != source:
path.append(parent[path[-1]])
return cost, tuple(reversed(path))
for v, weight in graph[u].items():
if v in settled or v in blocked_nodes or (u, v) in blocked_edges:
continue
candidate = cost + weight
if v not in distance or candidate < distance[v]:
distance[v], parent[v] = candidate, u
heappush(heap, (candidate, v))
return None
def yen(n, edges, source, target, k):
graph = prepare(n, edges, source, target, k)
if k == 0:
return []
first = shortest(graph, source, target, set(), set())
if first is None:
return []
accepted, candidates, seen = [first], [], {first[1]}
while len(accepted) < k:
previous = accepted[-1][1]
prefix_cost = 0
for i in range(len(previous) - 1):
root = previous[:i + 1]
forbidden = {(path[i], path[i + 1]) for _, path in accepted
if len(path) > i + 1 and path[:i + 1] == root}
spur = shortest(graph, root[-1], target, set(root[:-1]), forbidden)
if spur is not None:
tail_cost, tail = spur
path = root[:-1] + tail
if path not in seen:
seen.add(path)
heappush(candidates, (prefix_cost + tail_cost, path))
prefix_cost += graph[previous[i]][previous[i + 1]]
if not candidates:
break
accepted.append(heappop(candidates))
return accepted
def exhaustive(n, edges, source, target):
adjacency = [[] for _ in range(n)]
for u, v, weight in edges:
adjacency[u].append((v, weight))
result = []
def visit(path, cost):
if path[-1] == target:
result.append((cost, tuple(path)))
return
for v, weight in adjacency[path[-1]]:
if v not in path:
visit(path + [v], cost + weight)
visit([source], 0)
return sorted(result)
def check(n, edges, source, target, k):
before = tuple(edges)
answer = yen(n, edges, source, target, k)
oracle = exhaustive(n, edges, source, target)
assert [cost for cost, _ in answer] == [cost for cost, _ in oracle[:k]]
assert len({path for _, path in answer}) == len(answer)
assert all(item in oracle for item in answer)
assert tuple(edges) == before
assert answer == yen(n, edges, source, target, k)
def main():
edges = [(0, 1, 1), (1, 3, 1), (0, 2, 2), (2, 3, 2), (1, 2, 3)]
answer = yen(4, edges, 0, 3, 10)
assert answer == [(2, (0, 1, 3)), (4, (0, 2, 3)), (6, (0, 1, 2, 3))]
print("persistent candidate pool:", answer)
cyclic = [(0, 1, 1), (1, 3, 1), (1, 0, 0), (0, 2, 3), (2, 3, 0)]
print("root vertices cannot reappear:", yen(4, cyclic, 0, 3, 10))
zero = [(u, v, 0) for u in range(4) for v in range(4) if u != v]
all_zero = yen(4, zero, 0, 3, 64)
assert len(all_zero) == 5 and all(cost == 0 for cost, _ in all_zero)
check(4, zero, 0, 3, 64)
print("zero-weight complete digraph, simple paths:", len(all_zero))
assert yen(1, [], 0, 0, 64) == [(0, (0,))]
assert yen(2, [], 0, 1, 64) == []
assert yen(2, [], 0, 1, 0) == []
print("same endpoint / unreachable / K=0: passed")
pairs = [(u, v) for u in range(4) for v in range(4) if u != v]
for mask in range(1 << len(pairs)):
graph = [(u, v, (3 * u + v) % 4) for i, (u, v) in enumerate(pairs)
if mask >> i & 1]
check(4, graph, 0, 3, 64)
print("all four-vertex directed edge subsets:", 1 << len(pairs))
rng = Random(6907)
for _ in range(300):
n = rng.randrange(1, 8)
graph = [(u, v, rng.randrange(5)) for u in range(n) for v in range(n)
if u != v and rng.randrange(3) == 0]
check(n, graph, rng.randrange(n), rng.randrange(n), rng.randrange(13))
print("random graphs against all simple paths:", 300)
for args in [(2, [(0, 1, -1)], 0, 1, 2),
(2, [(0, 1, 1), (0, 1, 2)], 0, 1, 2),
(2, [(0, 0, 0)], 0, 1, 2), (2, [], 0, 1, True)]:
try:
yen(*args)
except ValueError as error:
print("rejected:", error)
else:
raise AssertionError("invalid graph accepted")
if __name__ == "__main__":
main()以下是上述程序的实际标准输出,供核对使用,不是需要另行执行的源码:
persistent candidate pool: [(2, (0, 1, 3)), (4, (0, 2, 3)), (6, (0, 1, 2, 3))] root vertices cannot reappear: [(2, (0, 1, 3)), (3, (0, 2, 3))] zero-weight complete digraph, simple paths: 5 same endpoint / unreachable / K=0: passed all four-vertex directed edge subsets: 4096 random graphs against all simple paths: 300 rejected: distinct directed edges and nonnegative integer weights required rejected: distinct directed edges and nonnegative integer weights required rejected: distinct directed edges and nonnegative integer weights required rejected: bounded graph, endpoints and K required
先把路径身份和返回数量约定清楚
输入是最多16个顶点的有向简单图,顶点编号从零开始,边权为零到一百万的整数。接口拒绝平行边、自环、负权和布尔值;每条路线的身份是它的完整顶点元组。
K可取零到64,返回至多K条不同的简单路径,费用非降。若图里只有三条可行路线,即使请求十条也只返回三条,不重复补齐。不可达时返回空列表;起点等于终点时,唯一答案是费用零的单顶点路径。
相同输入边序下结果可复现,但没有承诺所有等费用路线按全局字典序排列。候选堆用路径元组打破费用平局,只能排序当时已经生成的候选,不能替尚未生成的同费用路径提前排位。
一条路线可以在多个位置偏离
设上一条已接受路线为0、1、2、3。可以固定根前缀0,重新寻找从0到3的尾段;也可以固定0、1,再从1偏离;还可以固定0、1、2,从2偏离。
每个位置的root包含分叉点,shortest返回的tail也以这个分叉点开始。因此拼接采用root[:-1]加tail,避免把分叉点写两遍。prefix_cost只计算根前缀已经走过的边,再加新尾段费用。
代码按上一条路线从前向后推进prefix_cost。每处理完一个分叉点,才把通往下一点的边加入根费用;若提前加入,就把一条可能已被换掉的边算进新答案。
根前缀已经经过的点,尾段不能再回去
求尾段时禁用root[:-1]里的所有顶点,保留root[-1]作为尾段起点。即使尾段本身不重复顶点,它仍可能走回根前缀的旧点,拼接后形成重复访问。
程序的反例包含1到0的零权边。若根前缀为0、1,从1绕回0再去目标,会在完整路线中让0出现两次;它不能因为总费用有限就算作简单路径。
shortest在非负边权下按已定型顶点构造前驱,得到简单尾段;禁用旧根节点使尾段与根的其余部分互不相交。两项条件共同保证最终拼接路线没有重复顶点,零权环也不会产生无限答案。
禁边要检查全部已接受的同根路线
对当前root,查看所有已接受路径。凡是前面顶点序列与root相同,就禁用它紧接着root走出的那条有向边。不是禁掉整条旧路径,也不是只处理最近一条。
这样,新尾段必须在当前分叉位置选择一个还没有被这些已接受路线使用的下一步。那些仍与旧路线共享更长前缀、之后才改变的答案,会由更靠后的分叉位置负责。
不同分叉位置仍可能提出同一个完整候选,所以seen按完整顶点元组去重。它同时保留已生成和已接受的身份;同一简单图中,同一顶点序列费用固定,不存在以后需要用更低费用替换这份候选的情况。
两轮之间保留没有胜出的候选
样本第一条路线0、1、3费用二。展开它时,分叉点0产生0、2、3,费用四;分叉点1产生0、1、2、3,费用六。两条都进入候选堆,本轮只取费用四的路线。
下一轮展开费用四的路线,没有新的可行偏离,但费用六的旧候选仍然有效,应该成为第三条答案。如果每轮重新创建空堆,就会在这里错误地宣布只存在两条路线。
accepted和candidates因此承担不同角色:前者保存已经确认的排行,后者保存所有尚未选出的已发现路线。只删除本次真正弹出的最小候选,不随着上一条路线变化而清空其余内容。
为什么堆里的最小候选足以决定下一名
考虑任何尚未接受的简单路径P。比较它与当前全部已接受路线,取两者能共享的最长根前缀,并从共享此前缀的已接受路线中选最近接受的一条R。
在R被展开时,所有当前已接受且共享这个根前缀的路线都已经在列表中。P的下一条边不在该根下的禁边集合里,否则还能与某条已接受路线多共享一步,与最长性矛盾;P的尾段也不经过已固定的旧根点。
所以该次受限最短路能产生费用不大于P的候选。这个候选尚未被接受:否则它也会在同根禁边中被排除。若它以前已经生成,仍由候选堆保留。由此,对每个未接受答案都存在不更贵的可用候选,弹出堆最小值便不会越过更便宜的答案。
这个论证需要所有已接受路线都经过偏离展开,且候选跨轮保留。代码每次选下一名之前先展开最近接受的路线,正好补齐这一条件。
对子程序增加限制,不修改原图
shortest读取blocked_nodes和blocked_edges,在扫描邻接边时跳过它们。每个分叉位置重新计算自己的限制,没有在原邻接表上删边后再尝试恢复。
这避免一个分叉点的临时禁边污染下一个位置,也让输入图保持不变。接口先检查全部边,再处理K等于零或不可达情况,因此非法负边不会因为当前查询没走到那里而被悄悄接受。
代码保留普通Dijkstra的严格改善和过期堆项检查,并使用settled集合防止重新扫描已定型点。它没有改变负权边会破坏该子过程保证的边界。
裁判枚举完整简单路径,再比较排行费用
exhaustive从起点做独立深度优先枚举,每次只走向尚未出现在当前路径中的顶点,把所有到目标的路线列出并按费用排序。它没有根前缀禁边,也没有跨轮候选池。
比较时核对前K项的费用序列、输出路线确实存在、顶点序列不重复、输入未变,以及相同输入再次调用的结果一致。等费用组允许不同顺序,避免测试额外强加未承诺的字典序要求。
四顶点的十二条可能有向边形成4096个子图,全部与裁判比较;另外检查300张固定种子随机图。全零权四点完全有向图从0到3只有五条简单路径,即使存在大量零权环也完整结束。
计算量还包含前缀比较和保存候选
每条已接受路径最多展开V减一个分叉点,所以为前K条答案调用受限最短路的次数为O(KV)。这里的邻接表Dijkstra每次还需处理顶点、边和堆项,不能把整个排行算法的成本写成一次最短路。
教学实现会在每个分叉点扫描最多K条已接受路径,并比较长度至多V的前缀;另有路径复制、元组去重和堆比较。这些工作也要计入成本,没有直接套用其它优化实现的总复杂度。
最多生成O(KV)条候选,每条保存至多V个顶点,因此路径存储的上界为O(KV²),外加图与单次搜索空间。全部简单路径总数可能非常大,K上限控制的是本例交付规模,并不意味着全路径枚举适合大图。
参考资料
资料与本地实跑核查日期:2026年10月7日。程序、解释和教学样本独立组织;有限测试不代表生产性能评测。


