1502.K-shortest path

Time Limit: 1s Memory Limit: 256MB

Given a directed weighted graph with the possibility of having parallel edges, self-loops, and negative weights. The graph consists of $N$ nodes and $M$ directed edges. For every pair of nodes, determine the minimum distance achievable between them by traversing no more than $K$ directed edges, with the option of repeatedly passing through the same edge.

Formally speaking. Let edge $i$ go from node $u_i$ to $v_i$ with weight $w_i$. A path from $u$ to $v$ traversing $k$ edges is defined as an array $p$ of length $len_p = k$, where $1 \le p_i \le m, u_{p_1} = u, v_{p_k} = v, v_{p_i} = u_{p_{i + 1}}$ for $1 \le i < k$, and $dis_p = \sum_{i=1}^{k}w_{p_i}$ represents the distance of the path. For each $u$, $v$($1 \le u, v \le N $), you should calculate $\min_{p, len_p \le K}{dis_p}$.

Input Format(From the terminal/stdin)

The first line contains three integers: $N$, $M$, and $K (2 \le N \le 100, 1 \le M \le 10^4, 0 \le K \le 10^9)$.
The next $M$ lines each contain three integers: $u_i$, $v_i$, and $w_i$, indicating a directed edge from node $u_i$ to node $v_i$ with weight $w_i$ $(1 \le u_i, v_i \le N, -10^9 \le w_i \le 10^9)$.

Output Format(To the terminal/stdout)

Output an $N\times N$ matrix, where the element at row $i$ and column $j$ represents the minimum distance from node $i$ to node $j$ while traversing through at most $K$ edges. If it is not possible to reach node $j$ from node $i$, output "NO"(without quotes).

Sample Input 1

Copy
5 6 3
1 2 3
1 3 1
3 2 1
1 4 1
4 5 1
5 2 1
 · · \n
 · · \n
 · · \n
 · · \n
 · · \n
 · · \n
 · · \n

Sample Output 1

Copy
0 2 1 1 2
NO 0 NO NO NO
NO 1 0 NO NO
NO 2 NO 0 1
NO 1 NO NO 0
 · · · · \n
  · ·  ·  ·  \n
  · · ·  ·  \n
  · ·  · · \n
  · ·  ·  · \n

Sample Input 2

Copy
5 10 16
1 2 7
2 1 9
2 2 -1
2 1 -4
3 5 4
3 2 2
3 1 -3
4 5 2
5 5 0
5 3 -3
 ·  ·  \n
 · · \n
 · · \n
 · ·  \n
 · ·  \n
 · · \n
 · · \n
 · ·  \n
 · · \n
 · · \n
 · ·  \n

Sample Output 2

Copy
-11 -8 NO NO NO
-19 -16 NO NO NO
-16 -13 0 NO 4
-15 -12 -1 0 2
-18 -15 -3 NO 0
   ·  ·  ·  ·  \n
   ·   ·  ·  ·  \n
   ·   · ·  · \n
   ·   ·  · · \n
   ·   ·  ·  · \n
Source: The 2024 Hunan University Programming Contest

Submit

请先 登录

© 2025 FAQs