Under construction

Still being built. Things may change

Asteroid belt

Interview

Time limit1sMemory limit1024 MB

Summary
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 M×NM \times N 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 (X2,Y2)(X_2, Y_2).

Find the smallest amount of fuel Lukas needs to reach the destination.

Input

The first line contains the length MM and the height NN of the asteroid field.

The second line contains Lukas's starting coordinates X1X_1, Y1Y_1 and the destination coordinates X2X_2, Y2Y_2.

The third line contains a single integer KK, the number of empty regions.

Each of the next KK lines contains three natural numbers hih_i, aia_i, bib_i. This means that in row hih_i, squares aia_i through bib_i inclusive are empty.

Both the starting point and the destination belong to one of the KK 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 −1-1.

Constraints

1≤X1,X2≤M1 \le X_1, X_2 \le M

1≤Y1,Y2≤N1 \le Y_1, Y_2 \le N, 1≤ai≤bi≤M1 \le a_i \le b_i \le M

1≤hi≤N1 \le h_i \le N.

Examples1

  1. Example 1

    Input
    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
    
    Expected output
    5