Module: Floyd's algorithm


Problem

4 /10


The shortest way

Theory Click to read/hide

If a graph has cycles of negative weight, then formally the Floyd-Warshall algorithm is not applicable to such a graph.

In fact, for those pairs of vertices i and j, between which it is impossible to enter a cycle of negative weight, the algorithm will work correctly.

For the same pairs of vertices for which there is no answer (due to the presence of a negative cycle on the path between them), Floyd's algorithm will find some number (possibly strongly negative, but not necessarily) as an answer. However, Floyd's algorithm can be improved to handle such pairs of vertices neatly and output e.g. \(- \infty\).

To do this, for example, the following criterion "non-existence of the path" can be done. So, let the usual Floyd algorithm work on this graph. Then there is no shortest path between vertices i and j if and only if there is a vertex t reachable from i and from which j is reachable, for which  \(d [t][t]<0\).

In addition, when using Floyd's algorithm for graphs with negative cycles, it should be remembered that the distances that arise in the process of work can go negatively, exponentially with each phase. Therefore, you should take care against integer overflow by limiting all distances from below to some value (for example,  \(- \infty\)).

Verbally, the solution can be described as follows:
After the Floyd-Warshall algorithm has worked for the input graph, let's iterate over all pairs of vertices \((i,j)\), and for each such pair we check, infinitely the shortest path from i to j is small or not. To do this, let's iterate over the third vertex t, and if it turned out to be \(d[t][t] < 0\) (i.e. it lies in the cycle of negative weight), and it is reachable from i and j — then the path \((i,j)\) can be of infinitesimal length.

Problem

You are given a directed complete graph with some weights (lengths) assigned to its edges. Weights can be positive, negative or zero. We are interested in the minimum length of all possible paths between all pairs of distinct vertices in this graph. It will be necessary to find out if this minimum exists, and if it does, calculate it. (There is no minimum if it is possible to find a path of negative length in the graph, arbitrarily large in absolute value, tending to infinity).
 
Input
The first line is N≤50 vertices. Next comes the adjacency matrix of the graph, that is, N rows, each of which contains N numbers. The j-th number in the i-th row of the adjacency matrix specifies the length of the edge leading from the i-th vertex to the j-th one. Lengths can take any value from -1000000 to 1000000. It is guaranteed that there are zeros on the main diagonal of the matrix.
 
Output
Print a single number – desired minimum. If it doesn't exist, output  -1.
Examples
# Input Output
1
3
0 42 18468 
6335 0 26501 
19170 15725 0 
42
2
3
0 -7 3
-2 0 10
2 215 0 
-1