All problems

Problem 433

Shortest Paths in a DAG

Medium · 20 pts · Graph, Topological Sort, Shortest Path

Problem

A directed acyclic graph (DAG) has N nodes labelled 1 to N and weighted edges; weights may be negative, but since there are no cycles, shortest paths are still well defined. Print the shortest distance from node S to every node. Process the nodes in topological order and relax each node's outgoing edges once; this is faster than Dijkstra and, unlike Dijkstra, works with negative weights.

Input

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

Output

Print N values for nodes 1 to N, separated by spaces: the shortest distance, or INF if the node cannot be reached.

Constraints

1 <= N <= 100000; 0 <= M <= 200000; -1000 <= w <= 1000; the graph has no cycles

Example input

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

Example output

0 2 -1

Explanation

From S = 1, node 2 is reached directly with cost 2, and node 3 is reached through node 2 with cost 2 + (-3) = -1, which beats the direct edge of cost 4.

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

Previous: Minimum Cost to Connect Points Next: Count Paths in a DAG