Shortest Path

medium graphs dijkstra 2000 ms · 256 MB

Shortest Path

A country has n cities connected by m bidirectional roads. Road k connects cities u_k and v_k and takes w_k minutes to travel.

Find the minimum time to travel from city 1 to city n.

Input

The first line contains n and m (2 ≤ n ≤ 10^5, 0 ≤ m ≤ 2·10^5).

Each of the next m lines contains u v w (1 ≤ u, v ≤ n, 1 ≤ w ≤ 10^9). There may be multiple roads between the same pair of cities, and roads from a city to itself.

Output

Print the minimum travel time from city 1 to city n, or -1 if city n is unreachable.

Example 1

Input

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

Output

3

Example 2

Input

3 1
1 2 7

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

A plain breadth-first search counts roads, not minutes, so it cannot answer this directly. Which city should you finalise next so that its best time is already known to be correct?

Hint 2

Among the cities not yet finalised, the one with the smallest tentative time can never be improved later, because every weight is positive. Watch the sizes too: a route can be about 10^5 roads of weight 10^9 long.

Hint 3

This is a shortest-path problem with non-negative weights: Dijkstra's algorithm with a binary heap. If you push a city again whenever its time improves, older copies of it stay in the heap; make sure they cost almost nothing.

report an issue Prefer your own editor? sooks prep 3 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.