This page is still under construction.

Parts of this page are still being built. What you see may change.

The Hungary Games

Time limit2sMemory limit512 MB

Summary
Given a directed weighted graph, find the second smallest distinct total length among all walks from node 1 to node N, or -1 if fewer than two exist.
Level

Medium6 of 10

Topics
Shortest path, Graph, Heap, Dynamic programming
Solved
No attempts yet

Problem

Welcome to the Hungary Games! The streets of Budapest form a twisted network of one-way streets. As part of a reality TV show, you are forced to join a race through these streets, starting at the Szechenyi thermal bath (ss for short) and finishing at the Tomb of Gul Baba (tt for short).

Naturally, you want to finish as quickly as possible, because a better time earns you more promotional contracts. There is a catch, though: anyone clever enough to take a shortest ss-tt route is thrown into the Palvolgyi cave system and kept there as a national treasure. You would like to avoid that fate while still being as fast as possible, so you must take a strictly second-shortest ss-tt route.

Write a program that computes the length of a strictly second-shortest ss-tt route. Note that such a route may sometimes visit some nodes more than once — for instance, by traversing the same edge back and forth.

Input

The first line contains two integers NN and MM, where NN is the number of nodes in Budapest and MM is the number of edges. The nodes are numbered 1,2,…,N1, 2, \ldots, N; node 11 is ss and node NN is tt.

Each of the next MM lines contains three integers A B LA\ B\ L, describing a one-way street from AA to BB of length LL. You may assume that A≠BA \ne B on every line and that the ordered pairs (A,B)(A, B) are distinct.

Output

Output the length of a strictly second-shortest route from ss to tt — that is, the second smallest value among the distinct total lengths of all routes from ss to tt. If there are fewer than two distinct possible route lengths from ss to tt, output −1-1.

Constraints

Every length LL is a positive integer with 1≤L≤100001 \le L \le 10000. In 50% of the test cases, 2≤N≤402 \le N \le 40 and 0≤M≤10000 \le M \le 1000. In all test cases, 2≤N≤200002 \le N \le 20000 and 0≤M≤1000000 \le M \le 100000.

Examples2

  1. Example 1

    Input
    4 6
    1 2 5
    1 3 5
    2 3 1
    2 4 5
    3 4 5
    1 4 13
    
    Expected output
    11
    
  2. Example 2

    Input
    2 2
    1 2 1
    2 1 1
    
    Expected output
    3