Skills101
← All coding problems

Network Delay Time (Dijkstra's)

mediumGraphs+20 XPTime limit 2s

A network has n nodes 1 … n and directed links u v w: a signal sent from u reaches v after w time units. A signal starts at node k. How long until every node has received it? Print -1 if some node never does.

Input:

  • line 1: n m k
  • next m lines: u v w

Output: the time when the last node receives the signal, or -1.

Constraints: 1 ≤ n ≤ 10⁴, 0 ≤ m ≤ 5·10⁴, 0 ≤ w ≤ 10⁴; there may be several links between the same pair.

Think about it: this is the largest shortest-path distance from k. All weights are non-negative, so use Dijkstra's algorithm with a min-heap: O((n + m) log n).

Sample input 1

4 3 2
2 1 1
2 3 1
3 4 1

Sample output 1

2

Sample input 2

2 1 1
1 2 1

Sample output 2

1

Sample input 3

2 1 2
1 2 1

Sample output 3

-1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.