The Hungary Games
Time limit2sMemory limit512 MB
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 ( for short) and finishing at the Tomb of Gul Baba ( 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 - 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 - route.
Write a program that computes the length of a strictly second-shortest - 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 and , where is the number of nodes in Budapest and is the number of edges. The nodes are numbered ; node is and node is .
Each of the next lines contains three integers , describing a one-way street from to of length . You may assume that on every line and that the ordered pairs are distinct.
Output
Output the length of a strictly second-shortest route from to — that is, the second smallest value among the distinct total lengths of all routes from to . If there are fewer than two distinct possible route lengths from to , output .
Constraints
Every length is a positive integer with . In 50% of the test cases, and . In all test cases, and .