All Pairs Shortest Path

View as PDF

Submit solution

Points: 20 (partial)
Time limit: 0.4s
Java 2.0s
Memory limit: 512M

Author:
Problem types

You are given a graph with N vertices and M edges. Each edge is a directed edge from vertex ui to vertex vi with weight wi. You are asked to find the shortest path between all pairs of vertices. The graph may contain multiple edges between any pair of vertices, as well as self-loops. There may also be negative edge weights. It is not guaranteed that the graph is connected.

Constraints

For all subtasks:

0M4000

1ui,viN

Subtask 1 [10%]

1N300

109wi109

Subtask 2 [10%]

1N1000

1wi109

Subtask 3 [80%]

1N1000

109wi109

Input Specification

The first line contains 2 integers N and M, subject to the constraints above.

The next M lines describe the edges of the graph. Each line contains 3 integers, ui, vi, wi, indicating a directed edge from vertex ui to vertex vi with weight wi, subject to the constraints above.

Output Specification

This problem is graded with an identical checker. This includes whitespace characters. Ensure that every line of output is terminated with a \n character.

The output consists of N lines, each with N space separated integers. Each line should end with a new line character. Integer j on line i contains the distance of the shortest path from vertex i to vertex j.

If there is no path from i to j, INF should be printed instead of an integer.

If there is no lower bound on the length of the shortest path from i to j (or equivalently, there is a path from i to j that contains a negative edge cycle), -INF should be printed instead of an integer.

A negative edge cycle is a path that starts and ends on the same vertex, and the sum of the weights of those edges on that path is less than 0.

Sample Input 1

Copy
5 4
1 2 9
1 4 8
2 4 2
3 5 4

Sample Output 1

Copy
0 9 INF 8 INF
INF 0 INF 2 INF
INF INF 0 INF 4
INF INF INF 0 INF
INF INF INF INF 0

Sample Input 2

Copy
6 6
1 2 2
1 3 4
2 3 -10
3 5 1
5 6 2
6 5 -5

Sample Output 2

Copy
0 2 -8 INF -INF -INF
INF 0 -10 INF -INF -INF
INF INF 0 INF -INF -INF
INF INF INF 0 INF INF
INF INF INF INF -INF -INF
INF INF INF INF -INF -INF

Comments


  • 0
    stanwww  commented on Oct. 30, 2024, 4:05 a.m.

    I need hints.


  • 4
    Dingledooper  commented on March 10, 2020, 4:59 a.m.

    Floyd-Warshall passes, which is probably not intended.


    • 5
      wleung_bvg  commented on March 10, 2020, 8:52 a.m.

      Time limits have been adjusted.