CF BUDDY
← Problems·

1422D · Returning Home

2300 · graphs, shortest paths, sortings

Problem: Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.

Let's represent the city as an area of n×nn \times n square blocks. Yura needs to move from the block with coordinates (sx,sy)(s_x,s_y) to the block with coordinates (fx,fy)(f_x,f_y). In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are mm instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate xx or with the same coordinate yy as the location.

Help Yura to find the smallest time needed to get home.

Input Format: The first line contains two integers nn and mm — the size of the city and the number of instant-movement locations (1n1091 \le n \le 10^9, 0m1050 \le m \le 10^5).

The next line contains four integers sxs_x sys_y fxf_x fyf_y — the coordinates of Yura's initial position and the coordinates of his home (1sx,sy,fx,fyn 1 \le s_x, s_y, f_x, f_y \le n).

Each of the next mm lines contains two integers xix_i yiy_i — coordinates of the ii-th instant-movement location (1xi,yin1 \le x_i, y_i \le n).

Output Format: In the only line print the minimum time required to get home.

Note: In the first example Yura needs to reach (5,5)(5, 5) from (1,1)(1, 1). He can do that in 55 minutes by first using the second instant-movement location (because its yy coordinate is equal to Yura's yy coordinate), and then walking (4,1)(4,2)(4,3)(5,3)(5,4)(5,5)(4, 1) \to (4, 2) \to (4, 3) \to (5, 3) \to (5, 4) \to (5, 5).

Sample Cases

Case 1

Input

5 3
1 1 5 5
1 2
4 1
3 3

Output

5

Case 2

Input

84 5
67 59 41 2
39 56
7 2
15 3
74 18
22 7

Output

42

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback