All problems

Problem 269

Network Delay Time

Medium · 20 pts · Graph, Shortest Path, Heap

Problem

A network has N nodes labelled 1 to N and M directed connections. A connection u v w means a signal takes w time units to travel from u to v. A signal is sent from node K at time 0 and spreads along every connection. Print the time at which the last node receives the signal, or -1 if some node never receives it. Each node receives the signal at its shortest-path distance from K, so run Dijkstra's algorithm from K. The answer is the largest distance, or -1 if any node is unreachable.

Input

First line: integers N, M and K. Next M lines: a directed edge u v w.

Output

Print the time for all nodes to receive the signal, or -1.

Constraints

1 <= N <= 1000; 0 <= M <= 10000; 1 <= w <= 1000

Example input

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

Example output

2

Explanation

From node 2, the signal reaches nodes 1 and 3 at time 1, and then travels from 3 to node 4, arriving at time 2. Node 4 is the last, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Node With Maximum Degree Next: Cheapest Flights Within K Stops