atcoder#ABC273F. [ABC273F] Hammer 2
[ABC273F] Hammer 2
Score : points
Problem Statement
Takahashi is at the origin of a number line. Takahashi wants to reach the goal at coordinate .
Also, there are walls and hammers on the number line.
- At coordinates are walls of types , respectively.- Initially, Takahashi cannot get over the walls.
- Initially, Takahashi cannot get over the walls.
- At coordinates are hammers of types , respectively.- When he arrives at a coordinate with a hammer, he obtains the hammer.
- The hammer of type is dedicated to destroying the wall of type . After he obtains the hammer of type , he can destroy the wall of type and get over it.
- When he arrives at a coordinate with a hammer, he obtains the hammer.
- The hammer of type is dedicated to destroying the wall of type . After he obtains the hammer of type , he can destroy the wall of type and get over it.
Determine if he can reach the goal. If he can, find the minimum distance he travels.
Constraints
- All values in the input are integers.
- The coordinates and are distinct.
Input
The input is given from Standard Input in the following format:
Output
If Takahashi can reach the goal, print the minimum possible distance he travels as an integer.
Otherwise, print -1
.
3 10
-2 8 -5
5 -10 3
40
Takahashi can reach the goal by traveling a distance of as follows, which is the minimum possible:
- He starts at coordinate .
- He moves to coordinate to obtain the hammer of type .
- He moves to coordinate to obtain the hammer of type .
- He moves to coordinate to destroy the wall of type .
- He moves to coordinate to destroy the wall of type .
- He moves to coordinate to obtain the hammer of type .
- He moves to coordinate to destroy the wall of type .
- He moves to coordinate , which is the goal.
5 -1
10 -20 30 -40 50
-10 20 -30 40 -50
1
It may not be required that he obtains a hammer or destroys a wall to reach the goal.
1 100
30
60
-1
Takahashi cannot obtain the hammer of type , and neither can he reach the goal.
4 865942261
703164879 -531670946 -874856231 -700164975
-941120316 599462305 -649785130 665402307
4078987507