All problems

Problem 164

Dijkstra Shortest Distances

Medium · 20 pts · Graph, Shortest Path, Heap

Problem

You are given an undirected graph with N nodes labelled 1 to N and M edges, each with a positive weight. Print the shortest distance from node 1 to every node, for nodes 1 to N in order. The distance to node 1 itself is 0, and nodes that cannot be reached get -1. Use Dijkstra's algorithm with a priority queue: repeatedly take the unfinished node with the smallest known distance, mark it finished, and try to improve its neighbours' distances through it. Distances can exceed the 32-bit range, so use 64-bit integers.

Input

First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v w with weight w.

Output

Print N distances (for nodes 1..N), space-separated.

Constraints

1 <= N <= 100000; 0 <= M <= 200000; 1 <= w <= 1000000

Example input

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

Example output

0 1 3 4

Explanation

Node 2 is reached directly with distance 1. Node 3 has a direct edge of weight 4, but going through node 2 costs 1 + 2 = 3, which is cheaper. Node 4 is then reached from node 3 at 3 + 1 = 4. The distances are 0 1 3 4.

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

Previous: Shortest Path in an Unweighted Graph Next: Detect Cycle in an Undirected Graph