Asteroid belt
InterviewTime limit1sMemory limit1024 MB
Find the minimum vertical fuel needed to fly from the start square to the destination through empty row intervals, where horizontal flight is free.
- Level
Medium5 of 10
- Topics
- Shortest path, Intervals
- Solved
- No attempts yet
Problem
Many people think the Prienai Way asteroid belt is full of asteroids. Lukas has a map that shows the empty parts of the belt. On the map, the belt is divided into squares, and each square is either empty or full of asteroids.
Lukas wants to fly through the asteroid field. He can only fly through empty squares.
Lukas's spaceship can fly horizontally for as long as needed. Flying vertically uses fuel: 1 fuel unit for each square passed vertically. Lukas's destination is a planet in square .
Find the smallest amount of fuel Lukas needs to reach the destination.
Input
The first line contains the length and the height of the asteroid field.
The second line contains Lukas's starting coordinates , and the destination coordinates , .
The third line contains a single integer , the number of empty regions.
Each of the next lines contains three natural numbers , , . This means that in row , squares through inclusive are empty.
Both the starting point and the destination belong to one of the empty regions. No two empty regions in the same row touch or overlap.
Output
Print one integer, the smallest amount of fuel needed to reach the destination. If the destination cannot be reached, print .
Constraints
,
.