Asteroid belt | 프로그래밍의 벗 PivotOJ
PivotOJ

Asteroid belt

시간 제한: 1000ms메모리 제한: 1024MB출처: LMIO 2015-2016BOJ 30291

문제

Everyone thinks Prienai Way asteroid belt is filled with asteroids, but Lukas has a map with empty parts of the belt shown on it. In the map, asteroid belt is divided into M × N squares, each of which is either empty or full of asteroids.

Lukas wants to fly through the asteroid field. Naturally, he can only fly through empty squares.

Lukas’s spaceship can fly horizontally as long as needed, but it uses fuel to fly vertically – 1 fuel unit per each square passed vertically. Lukas’s destination is a planet in square (X2, Y2).

Figure out the smallest amount of fuel Lukas will need to consume to reach the destination.

입력

There are two numbers on the first line: asteroid field length M and height N. Lukas’s starting coordinates X1 and Y1, and the destination planet coordinates X2 ir Y2 are presented on the second line. The third line contains a single integer K – the number of empty regions.

Each of the following K lines consist of three natural numbers: hi, ai, bi, meaning that in hi-th row of the asteroid belt squares from ai to bi inclusively are free.

Both the starting point and the destination belongs to one of the K empty regions. No pair of empty regions that are on the same row touch or cross.

출력

Output one integer – lowest possible amount of fuel needed to reach the destination. If it is impossible to reach the destination, output -1.

예제

예제 1

입력
6 7
2 1 2 6
8
1 1 3
5 4 4
2 3 3
3 3 6
4 4 4
4 6 6
6 2 4
7 4 4
출력
5
코드를 제출하려면 로그인하세요.