Bellman-Ford
| Resources | |||||
|---|---|---|---|---|---|
| cp-algo | |||||
| cp-algo | 使用 Bellman-Ford 算法 | ||||
| CP2 | |||||
最短路径
重点例题 – 继续学习之前,请先尽力独立解决这道题!
解法
虽然这是单源最短路问题,但边权可能为负,因而不能使用通常的 Dijkstra 算法。可以改用 Bellman-Ford 算法:先考虑只使用一条边的路径,再计算最多使用两条边的路径,依此类推。若图中没有负环,则从源点到任意其他顶点的最短路径最多经过 条边,其中 是顶点数。因此,算法最多对所有边进行 轮松弛,时间复杂度为 。
若图中存在负环,再进行一轮松弛即可发现受其影响的顶点。在本题中,负环上的顶点到源点的距离视为负无穷;从这些顶点可达的所有顶点也同样如此。下面的解法会记录额外一轮松弛中发现的顶点,再以它们为起点进行 BFS。
代码实现
时间复杂度:
import queuen, m, q, s = map(int, input().split())while True:if n == 0 and m == 0 and q == 0 and s == 0:breakadj = [[] for _ in range(n)]for _ in range(m):u, v, w = map(int, input().split())
寻找负环
重点例题 – 继续学习之前,请先尽力独立解决这道题!
解法
如 cp-algorithms 所述,进行 轮边松弛。如果第 轮仍能更新距离,则存在负环。
INF = 10**18 # float('inf') will result in WA for some test casesdef bellman_ford(source: int):dist[source] = 0last_node_update = 0for i in range(1, n + 1):last_node_update = -1for (u, v, w) in graph:if dist[u] + w < dist[v]:
简单的线性规划
最短路算法也能解决下面这个简单的线性规划问题:
给定变量 ,以及形如 的约束,求一个可行解。
学习资源
| Resources | |||||
|---|---|---|---|---|---|
| MIT | 线性规划技巧 | ||||
练习题
Timeline(USACO 训练营):
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| RMI | Medium | Show TagsShortest Path | ||||
Floyd-Warshall
重点例题 – 继续学习之前,请先尽力独立解决这道题!
This section is not complete.
Any help would be appreciated! Just submit a Pull Request on GitHub.
(待补充讲解)
代码实现:全源最短路
INF = 10**18 # Note: using float('inf') results in TLEn, m, q = map(int, input().split())while True:if n == 0 and m == 0 and q == 0:breakdist = [[INF] * n for _ in range(n)]bad = [[0] * n for _ in range(n)]
练习题
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| APIO | Hard | Show TagsAPSP, Binary Search | ||||
修改后的 Dijkstra 算法
如果没有负环,前文介绍的 Dijkstra 代码仍能给出正确结果,但原有的时间复杂度上界不再成立。下面这道题的子任务 1 至 6 展示了这一点。
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| APIO | Hard | Show TagsShortest Path | ||||
这道题需要仔细分析本节介绍的三种最短路算法的内部工作方式,也能让你了解出题人如何构造针对算法的测试数据!