#P5905. 【模板】全源最短路(Johnson)
【模板】全源最短路(Johnson)
Problem Description
Given a directed graph with nodes and weighted edges, find the shortest path length between every pair of nodes. The length of a path is defined as the sum of the weights of all edges on the path.
Note:
- Edge weights may be negative, and the graph may contain multiple edges and self-loops.
- Some testdata is designed to make running SPFA for rounds fail.
Input Format
Line : Two integers , representing the number of nodes and the number of directed edges in the given graph.
Next lines: Each line contains three integers , meaning there is a directed edge of weight from node to node .
Output Format
If the graph contains a negative cycle, output only one line: .
If the graph does not contain a negative cycle:
Output lines. Let be the shortest path from to . On line , output . Note that this value may exceed the range of int.
If there is no path from to , then ; if , then .
5 7
1 2 4
1 4 10
2 3 7
4 5 3
4 2 -2
3 4 -3
5 3 4
128
1000000072
999999978
1000000026
1000000014
5 5
1 2 4
3 4 9
3 4 -3
4 5 3
5 3 -2
-1
Hint
[Sample Explanation]
The left figure shows the directed graph given in sample . The answer matrix formed by the shortest paths is:
0 4 11 8 11
1000000000 0 7 4 7
1000000000 -5 0 -3 0
1000000000 -2 5 0 3
1000000000 -1 4 1 0
The right figure shows the directed graph given in sample . The edges marked in red form a negative cycle. Note that the given graph may be disconnected.

[Constraints]
For of the data, $1\leq n\leq 3\times 10^3,\ \ 1\leq m\leq 6\times 10^3,\ \ 1\leq u,v\leq n,\ \ -3\times 10^5\leq w\leq 3\times 10^5$.
For of the data, , and there is no negative cycle (can be used to verify Floyd correctness).
For another of the data, (can be used to verify Dijkstra correctness).
upd. Added a set of hack testdata: targeting the SLF optimization of SPFA.
Translated by ChatGPT 5