Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/graf-barcha-masofalar

All-pairs distances

Medium 1000 ms 128 MB 58%
Share

A graph with $n$ vertices and $m$ directed edges is given; each edge has a length. For every pair $i$ and $j$ find the length of the shortest path from vertex $i$ to vertex $j$. If there is no path, print $-1$; the distance from a vertex to itself is $0$.

A weighted directed graph and the distance table obtained from it

Input

The first line contains two integers: $n$ and $m$. Each of the next $m$ lines contains three positive integers: $u$, $v$ and $w$ — an edge $u \to v$ of length $w$.

Output

$n$ lines of $n$ integers: the $j$-th number of the $i$-th line is the distance from $i$ to $j$ or $-1$.

Note

$1 \le n \le 100$
$0 \le m \le 10^{4}$
$1 \le u, v \le n$
$1 \le w \le 1000$
There may be multiple edges and loops.

Examples

Input #1
4 5
1 2 3
2 3 2
1 3 7
3 4 1
4 1 4
Output #1
0 3 5 6
7 0 2 3
5 8 0 1
4 7 9 0
Input #2
3 1
2 1 5
Output #2
0 -1 -1
5 0 -1
-1 -1 0

Sign in to submit a solution

Signing up is free and takes a minute.