atcoder#NIKKEI20192QUALD. Shortest Path on a Line
Shortest Path on a Line
Score : points
Problem Statement
We have points numbered to arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do operations to add edges in this graph. The -th operation is as follows:
- The operation uses integers and between and (inclusive), and a positive integer . For every pair of integers such that , add an edge of length between Vertex and Vertex .
The integers , , are all given as input.
Takahashi wants to solve the shortest path problem in the final graph obtained. Find the length of the shortest path from Vertex to Vertex in the final graph.
Constraints
Input
Input is given from Standard Input in the following format:
Output
Print the length of the shortest path from Vertex to Vertex in the final graph.
If there is no shortest path, print -1
instead.
4 3
1 3 2
2 4 3
1 4 6
5
We have an edge of length between Vertex and Vertex , and an edge of length between Vertex and Vertex , so there is a path of length between Vertex and Vertex .
4 2
1 2 1
3 4 2
-1
10 7
1 5 18
3 4 8
1 3 5
4 7 10
5 9 8
6 10 5
8 10 3
28