PrevNext

几乎所有金组最短路问题都会涉及 Dijkstra。不过 Bellman-Ford 和 Floyd-Warshall 更简单,最好先学习它们。

Bellman-Ford

Resources
CPH

截至但不包括“Negative Cycles”一节

Floyd-Warshall

教程

Resources
CPH

计算示例与代码

cp-algo

代码与正确性解释

PAPS

代码与正确性解释

CP2
Optional: 错误的 Floyd-Warshall

摘自这篇论文:

实现 Floyd-Warshall 算法时,一个常见错误是写错三重循环的顺序(正确顺序为 KIJ)。 错误的 IJK 和 IKJ 算法对某些实例无法得到正确答案。不过可以证明,将它们重复三次就能得到正确答案。

需要强调的是,这种修正方式(将错误算法重复三次)与正确的 Floyd-Warshall 算法只相差常数因子, 时间复杂度相同。因此我们的结果表明,如果不确定三重循环的顺序,可以保险起见把过程重复三次。

题目

重点例题 – 继续学习之前,请先尽力独立解决这道题!

讲解

本题要求计算任意两点之间的最短路。由于 NN 较小(N≤500N\le 500),并且存在负权边, 所以 Floyd-Warshall 很合适。

实现

时间复杂度: O(N3)\mathcal{O}(N^3)

Warning!

由于 Python 的常数较大,这段代码会在几个测试点上超时。

# 1e18 is used instead of float('inf') for performance reasons
BIG = int(1e18)
n, m, q = map(int, input().split())
min_dist = [[BIG] * n for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
a, b = a - 1, b - 1

题目

该算法是解决下列问题的第一步:

StatusSourceProblem NameDifficultyTags
GoldHard
Show TagsAPSP, DP

Dijkstra

教程

O(N2)\mathcal{O}(N^2)

Resources
cp-algo

O(Mlog⁡N)\mathcal{O}(M\log N)

O(Mlog⁡N)\mathcal{O}(M\log N) 实现

Resources
Benq

题目

重点例题 – 继续学习之前,请先尽力独立解决这道题!

实现

时间复杂度: O(N+Mlog⁡N)\mathcal{O}(N+M\log N)

下面的动画展示了算法的工作过程:

import heapq
n, m = map(int, input().split())
# Adjacency list of (neighbour, edge weight)
graph = [[] for _ in range(n)]
for i in range(m):
a, b, c = map(int, input().split())
graph[a - 1].append((b - 1, c))
Warning!

加入 continue 非常重要。它能保证在所有边权非负时,每个顶点的邻接表最多只会被遍历一次。 删掉它会使程序在上面问题的最后一个测试点超时!

最后一个测试点包含 100000100000 个目的地和 149997149997 个航班。城市 1 有飞往城市 2 到 50000 的航班, 城市 2 到 50000 都有飞往城市 50001 的航班,而城市 50001 有飞往城市 50002 到 100000 的航班。 如果没有 continue,程序从队列中弹出城市 1 到 50000 后,优先队列中会有 4999949999 条终点为城市 50001 的路线。 城市 50001 每次被弹出并处理时,都必须遍历它的所有出发航班(飞往城市 50002 到 100000)。 这会使运行时间达到 Θ(N2log⁡N)\Theta(N^2\log N),从而超时。

相反,如果加入 continue,程序第一次处理城市 50001 后,就再也不会遍历它的邻接表。

Optional: 更快的 Dijkstra

使用斐波那契堆可以做到 O(M+Nlog⁡N)\mathcal{O}(M+N\log N)。 但在实践中,由于斐波那契堆的常数很大,这种做法通常并不会更快。

题目

StatusSourceProblem NameDifficultyTags
CSESEasy
Show TagsShortest Path
GoldEasy
Show TagsShortest Path
GoldEasy
Show TagsShortest Path
GoldEasy
Show TagsShortest Path
GoldMedium
Show TagsShortest Path
GoldMedium
Show TagsShortest Path
CFMedium
Show TagsBinary Search, Coordinate Compression, DP, Shortest Path
CSESMedium
Show TagsShortest Path
KattisMedium
Show TagsShortest Path
CSESMedium
Show TagsShortest Path
ACHard
Show TagsGreedy, Shortest Path
IOIHard
Show TagsShortest Path
JOIHard
Show TagsDP, Shortest Path
JOIHard
Show TagsShortest Path
APIOHard
Show TagsGeometry, Shortest Path
Balkan OIHard
Show TagsShortest Path
Balkan OIVery Hard
Show TagsShortest Path, Stack

Module Progress:

PrevNext