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 \times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)$ to the block with coordinates $(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 $m$ 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 $x$ or with the same coordinate $y$ as the location.

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


-----Input-----

The first line contains two integers $n$ and $m$ — the size of the city and the number of instant-movement locations ($1 \le n \le 10^9$, $0 \le m \le 10^5$).

The next line contains four integers $s_x$ $s_y$ $f_x$ $f_y$ — the coordinates of Yura's initial position and the coordinates of his home ($ 1 \le s_x, s_y, f_x, f_y \le n$).

Each of the next $m$ lines contains two integers $x_i$ $y_i$ — coordinates of the $i$-th instant-movement location ($1 \le x_i, y_i \le n$).


-----Output-----

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


-----Examples-----
Input
5 3
1 1 5 5
1 2
4 1
3 3

Output
5

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

Output
42



-----Note-----

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

Source: codeforces | Difficulty: HARD
Tags: Sorting

Graph algorithms

Shortest paths


Solutions:
class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def multi_add(self, _from, _to, _cost):
		self.add(_from, _to, _cost)
		self.add(_to, _from, _cost)

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		pv = [-1 for i in range(self.V)]
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					pv[e.to] = v
					heapq.heappush(que, (d[e.to], e.to))
		return d

	def path(self, s, e):
		(d, pv) = self.shortest_path(s)
		res = [e]
		while res[-1] != s:
			res.append(pv[res[-1]])
		return res
import sys
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
p = []
for i in range(m):
	p.append(tuple(map(int, input().split())))
chinerist = Dijkstra(m + 2)
city = [i for i in range(m)]
city.sort(key=lambda i: p[i][0])
for i in range(1, m):
	(u, v) = (city[i - 1], city[i])
	chinerist.multi_add(u + 1, v + 1, p[v][0] - p[u][0])
city.sort(key=lambda i: p[i][1])
for i in range(1, m):
	(u, v) = (city[i - 1], city[i])
	chinerist.multi_add(u + 1, v + 1, p[v][1] - p[u][1])
for i in range(m):
	(x, y) = p[i]
	chinerist.add(0, i + 1, min(abs(sx - x), abs(sy - y)))
	chinerist.add(i + 1, m + 1, abs(fx - x) + abs(fy - y))
chinerist.add(0, m + 1, abs(sx - fx) + abs(sy - fy))
ans = chinerist.shortest_path(0)[m + 1]
print(ans)


import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict
import heapq as hq
import math

def dijkstra(G, s):
	n = len(G)
	visited = [False] * n
	weights = [math.inf] * n
	path = [None] * n
	queue = []
	weights[s] = 0
	hq.heappush(queue, (0, s))
	while len(queue) > 0:
		(g, u) = hq.heappop(queue)
		visited[u] = True
		for (v, w) in G[u]:
			if not visited[v]:
				f = g + w
				if f < weights[v]:
					weights[v] = f
					path[v] = u
					hq.heappush(queue, (f, v))
	return (path, weights)

def solve(grid, sx, sy, ex, ey):
	console('----- solving ------')
	minres = abs(sx - ex) + abs(sy - ey)
	console(minres)
	if grid == []:
		return minres
	d = defaultdict(list)
	grid = [(i, x, y) for (i, (x, y)) in enumerate(grid)]
	grid = sorted(grid, key=lambda x: x[1])
	for ((i1, x1, y1), (i2, x2, y2)) in zip(grid, grid[1:]):
		d[i1].append((i2, x2 - x1))
		d[i2].append((i1, x2 - x1))
	grid = sorted(grid, key=lambda x: x[2])
	for ((i1, x1, y1), (i2, x2, y2)) in zip(grid, grid[1:]):
		d[i1].append((i2, y2 - y1))
		d[i2].append((i1, y2 - y1))
	for (i, x, y) in grid:
		d[-2].append((i, abs(x - sx)))
		d[-2].append((i, abs(y - sy)))
		d[i].append((-1, abs(x - ex) + abs(y - ey)))
	d[-1] = []
	console(d.keys())
	idxs = {k: i for (i, k) in enumerate(d.keys())}
	G = [[] for _ in range(len(idxs))]
	for (e, vrr) in d.items():
		for (v, cost) in vrr:
			G[idxs[e]].append((idxs[v], cost))
	(_, costs) = dijkstra(G, idxs[-2])
	res = costs[idxs[-1]]
	return min(minres, res)

def console(*args):
	return
inp = sys.stdin.readlines()
for case_num in [1]:
	(_, nrows) = list(map(int, inp[0].split()))
	(sx, sy, ex, ey) = list(map(int, inp[1].split()))
	currow = 2
	grid = []
	for _ in range(nrows):
		grid.append(list(map(int, inp[currow].split())))
		currow += 1
	res = solve(grid, sx, sy, ex, ey)
	print(res)


import sys
input = sys.stdin.readline
import heapq

def dijkstra(n, s, edges):
	hq = [(0, s)]
	cost = [float('inf')] * n
	cost[s] = 0
	while hq:
		(c, v) = heapq.heappop(hq)
		if c > cost[v]:
			continue
		for (d, u) in edges[v]:
			tmp = d + cost[v]
			if tmp < cost[u]:
				cost[u] = tmp
				heapq.heappush(hq, (tmp, u))
	return cost[1]

def main():
	(n, m) = map(int, input().split())
	(sx, sy, fx, fy) = map(int, input().split())
	xy = [list(map(int, input().split())) + [i + 2] for i in range(m)]
	edges = [[] for _ in range(m + 2)]
	xy.sort(key=lambda x: x[0])
	for i in range(m - 1):
		dx = abs(xy[i][0] - xy[i + 1][0])
		dy = abs(xy[i][1] - xy[i + 1][1])
		d = min(dx, dy)
		pos1 = xy[i][2]
		pos2 = xy[i + 1][2]
		edges[pos1].append((d, pos2))
		edges[pos2].append((d, pos1))
	xy.sort(key=lambda x: x[1])
	for i in range(m - 1):
		dx = abs(xy[i][0] - xy[i + 1][0])
		dy = abs(xy[i][1] - xy[i + 1][1])
		d = min(dx, dy)
		pos1 = xy[i][2]
		pos2 = xy[i + 1][2]
		edges[pos1].append((d, pos2))
		edges[pos2].append((d, pos1))
	for (x, y, i) in xy:
		d1 = min(abs(x - sx), abs(y - sy))
		d2 = abs(x - sx) + abs(y - sy)
		edges[0].append((d1, i))
		edges[i].append((d2, 0))
		d1 = min(abs(x - fx), abs(y - fy))
		d2 = abs(x - fx) + abs(y - fy)
		edges[1].append((d1, i))
		edges[i].append((d2, 1))
	d = abs(sx - fx) + abs(sy - fy)
	edges[0].append((d, 1))
	edges[1].append((d, 0))
	ans = dijkstra(m + 2, 0, edges)
	print(ans)
main()


from sys import stdin

class Input:

	def __init__(self):
		self.it = iter(stdin.readlines())

	def line(self):
		return next(self.it).strip()

	def array(self, sep=' ', cast=int):
		return list(map(cast, self.line().split(sep=sep)))

def testcases(unknown=False):
	inpt = Input()

	def testcases_decorator(func):
		(cases,) = [float('Inf')] if unknown else inpt.array()
		while cases > 0:
			try:
				func(inpt)
				cases -= 1
			except StopIteration:
				break
	return testcases_decorator
import heapq

class Graph:

	def __init__(self, n):
		self.n = n
		self.g = [{} for i in range(n)]
		self.oo = float('Inf')

	def add_edge(self, u, v, w):
		self.g[u][v] = min(w, self.g[u].get(v, self.oo))

	def dijkstra(self, s):
		dist = [self.oo for i in range(self.n)]
		mask = (1 << 17) - 1
		dist[s] = 0
		pq = []
		heapq.heappush(pq, s)
		while pq:
			x = heapq.heappop(pq)
			d = x >> 17
			u = x & mask
			if dist[u] != d:
				continue
			for (v, w) in self.g[u].items():
				if d + w < dist[v]:
					dist[v] = d + w
					heapq.heappush(pq, dist[v] << 17 | v)
		return dist

@testcases(unknown=True)
def solve(inpt):
	X = 0
	Y = 1
	(n, m) = inpt.array()
	(sx, sy, fx, fy) = inpt.array()
	g = Graph(m + 2)
	d = abs(fx - sx) + abs(fy - sy)
	g.add_edge(m, m + 1, d)
	g.add_edge(m + 1, m, d)
	x = [None for i in range(m)]
	y = [None for i in range(m)]
	for i in range(m):
		(x[i], y[i]) = inpt.array()
		g.add_edge(m, i, min(abs(x[i] - sx), abs(y[i] - sy)))

	def add_edges(p, x):
		le = 0
		ri = 0
		while le < m:
			u = p[le]
			ri = le + 1
			while ri < m and x[u] == x[p[ri]]:
				v = p[ri]
				g.add_edge(u, v, 0)
				g.add_edge(v, u, 0)
				ri += 1
			if le:
				v = p[le - 1]
				d = x[u] - x[v]
				g.add_edge(u, v, d)
				g.add_edge(v, u, d)
			le = ri
	p = [i for i in range(m)]
	p.sort(key=lambda p: x[p])
	add_edges(p, x)
	p = [i for i in range(m)]
	p.sort(key=lambda p: y[p])
	add_edges(p, y)
	d = g.dijkstra(m)
	ans = d[m + 1]
	for i in range(m):
		ans = min(ans, d[i] + abs(fx - x[i]) + abs(fy - y[i]))
	print(ans)


from heapq import heappush, heappop
import os
import io
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def li():
	return [int(i) for i in input().rstrip().split()]
(n, m) = li()
(sx, sy, fx, fy) = li()
s = (sx, sy)
instant = [s]
for i in range(m):
	(x, y) = li()
	instant.append((x, y))
g = {(x, y): set() for (x, y) in instant}
w = {}

def build_axis(instant_slots):
	for i in range(1, len(instant_slots)):
		(x1, y1) = instant_slots[i - 1]
		(x2, y2) = instant_slots[i]
		v1 = (x1, y1)
		v2 = (x2, y2)
		c = min(abs(x1 - x2), abs(y1 - y2))
		if v2 != s:
			g[v1].add(v2)
			w[v1, v2] = c
		if v1 != s:
			g[v2].add(v1)
			w[v2, v1] = c
instant_x = sorted(instant)
build_axis(instant_x)
instant_y = sorted(instant, key=lambda pos: pos[1])
build_axis(instant_y)

def dijsktra():
	d = {(x, y): inf for (x, y) in instant}
	d[s] = 0
	q = [(0, s)]
	while q:
		(_, u) = heappop(q)
		for v in g[u]:
			x = d[u] + w[u, v]
			if x < d[v]:
				d[v] = x
				heappush(q, (d[v], v))
	return d
d = dijsktra()
print(min([d[x, y] + abs(x - fx) + abs(y - fy) for (x, y) in instant]))


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def comb(n, r):
	if n < r:
		return 0
	else:
		return fac[n] * (finv[r] * finv[n - r] % mod) % mod

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

def dijkstra(N, G, s):
	dist = [INF] * N
	que = [(0, s)]
	dist[s] = 0
	while que:
		(c, v) = heappop(que)
		if dist[v] < c:
			continue
		for (t, cost) in G[v]:
			if dist[v] + cost < dist[t]:
				dist[t] = dist[v] + cost
				heappush(que, (dist[t], t))
	return dist

def solve():
	from heapq import heappop, heappush

	def ip_dis(x, y, k, l):
		return min(abs(k - x), abs(l - y))

	def fp_dis(x, y, k, l):
		return abs(k - x) + abs(l - y)
	inf = 10 ** 10
	(n, m) = sep()
	(sx, sy, fx, fy) = sep()
	G = [[] for _ in range(m + 2)]
	ps = []
	for i in range(1, m + 1):
		(x, y) = sep()
		ps.append((i, x, y))
		G[0].append((i, ip_dis(sx, sy, x, y)))
		G[i].append((m + 1, fp_dis(x, y, fx, fy)))
	ps.sort(key=lambda x: x[1])
	for i in range(m - 1):
		d = ps[i + 1][1] - ps[i][1]
		G[ps[i][0]].append((ps[i + 1][0], d))
		G[ps[i + 1][0]].append((ps[i][0], d))
	ps.sort(key=lambda x: x[2])
	for i in range(m - 1):
		d = ps[i + 1][2] - ps[i][2]
		G[ps[i][0]].append((ps[i + 1][0], d))
		G[ps[i + 1][0]].append((ps[i][0], d))
	G[0].append((m + 1, fp_dis(sx, sy, fx, fy)))
	res = {i: inf for i in range(m + 2)}
	visited = {i: True for i in range(m + 2)}
	q = [(0, 0)]
	while q:
		(d, v) = heappop(q)
		if visited[v]:
			visited[v] = False
			for (u, l) in G[v]:
				if l + d < res[u]:
					res[u] = l + d
					heappush(q, (res[u], u))
	print(res[m + 1])
solve()


from heapq import heappush, heappop
import sys
input = sys.stdin.readline
INF = 10 ** 10

def dijkstra(N, G, s):
	dist = [INF] * N
	que = [(0, s)]
	dist[s] = 0
	while que:
		(c, v) = heappop(que)
		if dist[v] < c:
			continue
		for (t, cost) in G[v]:
			if dist[v] + cost < dist[t]:
				dist[t] = dist[v] + cost
				heappush(que, (dist[t], t))
	return dist[1]
(N, M) = list(map(int, input().split()))
(sx, sy, fx, fy) = list(map(int, input().split()))
vs = []
g = [set() for _ in range(M + 2)]
for i in range(M):
	(x, y) = list(map(int, input().split()))
	g[0].add((i + 2, min(abs(x - sx), abs(y - sy))))
	g[i + 2].add((1, abs(x - fx) + abs(y - fy)))
	vs.append((i + 2, x, y))
vs.sort(key=lambda x: (x[1], x[2]))
for ((b, bx, by), (i, x, y)) in zip(vs, vs[1:]):
	c = min(x - bx, abs(y - by))
	g[i].add((b, c))
	g[b].add((i, c))
vs.sort(key=lambda x: (x[2], x[1]))
for ((b, bx, by), (i, x, y)) in zip(vs, vs[1:]):
	c = min(abs(x - bx), y - by)
	g[i].add((b, c))
	g[b].add((i, c))
print(min(dijkstra(M + 2, g, 0), abs(fy - sy) + abs(fx - sx)))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from heapq import *
from collections import defaultdict as dc
inf = 3 * 10 ** 9
(n, m) = RL()
(sx, sy, fx, fy) = RL()
g = [RLL() for _ in range(m)]
(xx, yy) = (set((a[0] for a in g)), set((a[1] for a in g)))
xx = list(sorted(xx))
yy = list(sorted(yy))
(xn, yn) = (len(xx), len(yy))
dic = dc(list)
for i in range(xn - 1):
	d = xx[i + 1] - xx[i]
	dic[xx[i]].append((xx[i + 1], d))
	dic[xx[i + 1]].append((xx[i], d))
for i in range(yn - 1):
	d = yy[i + 1] - yy[i]
	dic[-yy[i + 1]].append((-yy[i], d))
	dic[-yy[i]].append((-yy[i + 1], d))
for (x, y) in g:
	d = min(abs(x - sx), abs(y - sy))
	dic[x].append((-y, 0))
	dic[-y].append((x, 0))
	dic[x].append((0.5, d))
heap = []
dist = dc(lambda : inf)
for (x, y) in g:
	d = abs(fx - x) + abs(fy - y)
	if dist[x] <= d:
		continue
	dist[x] = d
	heappush(heap, (d, x))
ans = abs(sx - fx) + abs(sy - fy)
while heap:
	(d, node) = heappop(heap)
	if d > ans or node == 0.5:
		ans = min(ans, d)
		break
	if d > dist[node]:
		continue
	dist[node] = d
	for (pre, w) in dic[node]:
		s = d + w
		if dist[pre] <= s:
			continue
		dist[pre] = s
		heappush(heap, (s, pre))
print(ans)


import os
import sys
from io import BytesIO, IOBase
from heapq import heappush, heappop
tupleMOD = 10 ** 10
INF = 10 ** 17

def minDist(a, b):
	yDist = abs(a % tupleMOD - b % tupleMOD)
	xDist = abs(a // tupleMOD - b // tupleMOD)
	return min(xDist, yDist)

def main():
	(n, m) = map(int, input().split())
	(sx, sy, fx, fy) = map(int, input().split())
	points = []
	pointsX = []
	pointsY = []
	dist = [INF] * m
	adjList = []
	for i in range(m):
		(x, y) = map(int, input().split())
		points.append(tupleMOD * x + y)
		pointsX.append(tupleMOD * x + i)
		pointsY.append(tupleMOD * y + i)
		adjList.append([])
	pointsX.sort()
	pointsY.sort()
	for i in range(m - 1):
		con1 = pointsX[i] % tupleMOD
		con2 = pointsX[i + 1] % tupleMOD
		distP = minDist(points[con1], points[con2])
		adjList[con1].append(con2 * tupleMOD + distP)
		adjList[con2].append(con1 * tupleMOD + distP)
		con1 = pointsY[i] % tupleMOD
		con2 = pointsY[i + 1] % tupleMOD
		distP = minDist(points[con1], points[con2])
		adjList[con1].append(con2 * tupleMOD + distP)
		adjList[con2].append(con1 * tupleMOD + distP)
	pqueue = []
	for i in range(m):
		heappush(pqueue, i + tupleMOD * minDist(sx * tupleMOD + sy, points[i]))
		dist[i] = minDist(sx * tupleMOD + sy, points[i])
	while pqueue:
		elem = heappop(pqueue)
		loc = elem % tupleMOD
		if elem // tupleMOD != dist[loc]:
			continue
		for edge in adjList[loc]:
			length = edge % tupleMOD
			point = edge // tupleMOD
			if dist[point] > dist[loc] + length:
				dist[point] = dist[loc] + length
				heappush(pqueue, point + tupleMOD * dist[point])
	ans = abs(fx - sx) + abs(fy - sy)
	for i in range(m):
		if ans > dist[i] + abs(fx - points[i] // tupleMOD) + abs(fy - points[i] % tupleMOD):
			ans = dist[i] + abs(fx - points[i] // tupleMOD) + abs(fy - points[i] % tupleMOD)
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys, io, os
import math
import heapq as hq
import random
from collections import defaultdict
import sys
from os import path

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	pass
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def console(*args):
		pass
if True:
	inp = iter(sys.stdin.buffer.readlines())
	input = lambda : next(inp)
else:
	input = sys.stdin.buffer.readline

def solve(*args):
	console('----- solving ------')
	console(*args)
	console('----- ------- ------')
	return solve_(*args)

def solve_(grid, sx, sy, ex, ey):
	minres = abs(sx - ex) + abs(sy - ey)
	console(minres)
	if grid == []:
		return minres
	d = defaultdict(list)
	grid = [(i, x, y) for (i, (x, y)) in enumerate(grid)]
	grid = sorted(grid, key=lambda x: x[1])
	for ((i1, x1, y1), (i2, x2, y2)) in zip(grid, grid[1:]):
		d[i1].append((i2, x2 - x1))
		d[i2].append((i1, x2 - x1))
	grid = sorted(grid, key=lambda x: x[2])
	for ((i1, x1, y1), (i2, x2, y2)) in zip(grid, grid[1:]):
		d[i1].append((i2, y2 - y1))
		d[i2].append((i1, y2 - y1))
	for (i, x, y) in grid:
		d[-2].append((i, abs(x - sx)))
		d[-2].append((i, abs(y - sy)))
		d[i].append((-1, abs(x - ex) + abs(y - ey)))
	res = dijkstra_with_preprocessing(d, -2, -1)
	return min(minres, res)

def dijkstra_with_preprocessing(map_from_node_to_nodes_and_costs, source, target):
	d = map_from_node_to_nodes_and_costs
	if target not in d:
		d[-1] = []
	idxs = {k: i for (i, k) in enumerate(d.keys())}
	G = [[] for _ in range(len(idxs))]
	for (e, vrr) in d.items():
		for (v, cost) in vrr:
			G[idxs[e]].append((idxs[v], cost))
	(_, costs) = dijkstra(G, idxs[source])
	return costs[idxs[target]]

def dijkstra(G, s):
	n = len(G)
	visited = [False] * n
	weights = [math.inf] * n
	path = [None] * n
	queue = []
	weights[s] = 0
	hq.heappush(queue, (0, s))
	while len(queue) > 0:
		(g, u) = hq.heappop(queue)
		visited[u] = True
		for (v, w) in G[u]:
			if not visited[v]:
				f = g + w
				if f < weights[v]:
					weights[v] = f
					path[v] = u
					hq.heappush(queue, (f, v))
	return (path, weights)
for case_num in [1]:
	(_, nrows) = list(map(int, input().split()))
	(sx, sy, ex, ey) = list(map(int, input().split()))
	grid = []
	for z in range(nrows):
		grid.append(list(map(int, input().split())))
	res = solve(grid, sx, sy, ex, ey)
	print(res)


import heapq

def main():
	(n, m) = map(int, input().split())
	(sx, sy, fx, fy) = map(int, input().split())
	sub = {i: 0 for i in range(m + 1)}
	sub[0] = (sx, sy)
	dx = []
	dy = []
	for i in range(m):
		(x, y) = map(int, input().split())
		dx.append((x, i + 1))
		dy.append((y, i + 1))
		sub[i + 1] = (x, y)
	dx.append((sx, 0))
	dy.append((sy, 0))
	dx.sort()
	dy.sort()
	G = [[] for i in range(m + 2)]
	d = [2 * 10 ** 9] * (m + 2)
	for i in range(m):
		(px, pindex) = dx[i]
		(nx, nindex) = dx[i + 1]
		G[pindex].append((nx - px, nindex))
		G[nindex].append((nx - px, pindex))
	for i in range(m):
		(py, pindex) = dy[i]
		(ny, nindex) = dy[i + 1]
		G[pindex].append((ny - py, nindex))
		G[nindex].append((ny - py, pindex))
	for i in range(m + 1):
		(x, y) = sub[i]
		min_cost = abs(y - fy) + abs(x - fx)
		G[m + 1].append((min_cost, i))
		G[i].append((min_cost, m + 1))
	que = []
	heapq.heapify(que)
	d[0] = 0
	heapq.heappush(que, (0, 0))
	while que:
		(cost, v) = heapq.heappop(que)
		if d[v] < cost:
			continue
		for (cost, node) in G[v]:
			if d[node] > d[v] + cost:
				d[node] = d[v] + cost
				heapq.heappush(que, (d[node], node))
	ans = d[m + 1]
	print(ans)
	return
main()


import heapq
s = input().split(' ')
n = int(s[0])
m = int(s[1])
s = input().split(' ')
sx = int(s[0])
sy = int(s[1])
fx = int(s[2])
fy = int(s[3])
tmp = [0] * (m + 2)
tmp[0] = (sx, sy)
tmpx = []
tmpy = []
tmpx.append((sx, 0))
tmpy.append((sy, 0))
for i in range(m):
	(x, y) = map(int, input().split())
	tmpx.append((x, i + 1))
	tmpy.append((y, i + 1))
	tmp[i + 1] = (x, y)
tmpx.sort()
tmpy.sort()
graph = [[] for i in range(m + 2)]
d = [2 * 10 ** 9] * (m + 2)
for i in range(m):
	(px, pindex) = tmpx[i]
	(nx, nindex) = tmpx[i + 1]
	graph[pindex].append((nx - px, nindex))
	graph[nindex].append((nx - px, pindex))
	(py, pindex) = tmpy[i]
	(ny, nindex) = tmpy[i + 1]
	graph[pindex].append((ny - py, nindex))
	graph[nindex].append((ny - py, pindex))
for i in range(m + 1):
	(x, y) = tmp[i]
	min = abs(y - fy) + abs(x - fx)
	graph[m + 1].append((min, i))
	graph[i].append((min, m + 1))
heap = []
heapq.heapify(heap)
d[0] = 0
heapq.heappush(heap, (0, 0))
while heap:
	(cost, v) = heapq.heappop(heap)
	if d[v] < cost:
		continue
	for (cost, node) in graph[v]:
		if d[node] > d[v] + cost:
			d[node] = d[v] + cost
			heapq.heappush(heap, (d[node], node))
ans = d[m + 1]
print(ans)


from heapq import *
import sys
F = 9 ** 99
p = lambda : map(int, sys.stdin.readline().split())
a = abs
(N, M) = p()
(A, B, C, D) = p()
e = []
g = [set() for _ in range(M + 2)]
for i in range(M):
	(x, y) = p()
	g[0].add((i + 2, min(a(x - A), a(y - B))))
	g[i + 2].add((1, a(x - C) + a(y - D)))
	e.append((i + 2, x, y))
for k in [1, 2]:
	e.sort(key=lambda x: x[k])
	for ((b, G, H), (i, x, y)) in zip(e, e[1:]):
		c = x - G if k < 2 else y - H
		g[i].add((b, c))
		g[b].add((i, c))
d = [F] * (M + 2)
q = [(0, 0)]
d[0] = 0
while q:
	(c, v) = heappop(q)
	if d[v] < c:
		continue
	for (t, e) in g[v]:
		if d[v] + e < d[t]:
			d[t] = d[v] + e
			heappush(q, (d[t], t))
print(min(d[1], a(D - B) + a(C - A)))


import sys
input = sys.stdin.readline
from collections import defaultdict
from operator import itemgetter
import heapq
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
graph = defaultdict(list)
(instant, ans_) = ([], [1 << 40])

def ans(t, x, y):
	ans_[0] = min(ans_[0], t + abs(fx - x) + abs(fy - y))
for i in range(m):
	(x, y) = map(int, input().split())
	instant.append((x, y, i))
instant.append((sx, sy, m))
ins_x = sorted(instant, key=itemgetter(0))
ins_y = sorted(instant, key=itemgetter(1))
time = [1 << 40] * (m + 1)
time[m] = 0
for i in range(1, m + 1):
	(x0, y0, m0) = ins_x[i - 1]
	(x1, y1, m1) = ins_x[i]
	graph[m0].append((m1, min(abs(x1 - x0), abs(y1 - y0))))
	graph[m1].append((m0, min(abs(x1 - x0), abs(y1 - y0))))
	(x0, y0, m0) = ins_y[i - 1]
	(x1, y1, m1) = ins_y[i]
	graph[m0].append((m1, min(abs(x1 - x0), abs(y1 - y0))))
	graph[m1].append((m0, min(abs(x1 - x0), abs(y1 - y0))))
queue = [(0, m)]
while queue:
	(t, town) = heapq.heappop(queue)
	if time[town] < t:
		continue
	ans(t, instant[town][0], instant[town][1])
	for (to, cost) in graph[town]:
		if time[to] > time[town] + cost:
			time[to] = time[town] + cost
			heapq.heappush(queue, (time[to], to))
print(ans_[0])


import sys
import math
from heapq import heappush, heappop

def read_graph(s, n, m):
	graph = {}
	inst_mov_loc = []
	for i in range(0, m):
		(a, b) = map(int, sys.stdin.readline().split())
		inst_mov_loc.append((a, b))
	inst_mov_loc.append(s)
	inst_mov_loc.sort(key=lambda x: x[0])
	for i in range(0, len(inst_mov_loc)):
		if i == 0 and len(inst_mov_loc) > 1:
			graph[inst_mov_loc[i]] = [(inst_mov_loc[i + 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i + 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i + 1][1])))]
			continue
		if i == m:
			graph[inst_mov_loc[i]] = [(inst_mov_loc[i - 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i - 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i - 1][1])))]
			continue
		graph[inst_mov_loc[i]] = [(inst_mov_loc[i - 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i - 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i - 1][1])))]
		graph[inst_mov_loc[i]].append((inst_mov_loc[i + 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i + 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i + 1][1]))))
	inst_mov_loc.sort(key=lambda x: x[1])
	for i in range(0, len(inst_mov_loc)):
		if i > 0:
			if inst_mov_loc[i - 1] not in graph[inst_mov_loc[i]]:
				graph[inst_mov_loc[i]].append((inst_mov_loc[i - 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i - 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i - 1][1]))))
		if i < m:
			if inst_mov_loc[i + 1] not in graph[inst_mov_loc[i]]:
				graph[inst_mov_loc[i]].append((inst_mov_loc[i + 1], min(abs(inst_mov_loc[i][0] - inst_mov_loc[i + 1][0]), abs(inst_mov_loc[i][1] - inst_mov_loc[i + 1][1]))))
	return graph

def dijkstra(graph, s):
	q = [(0, s)]
	count = 0
	d = {i: -1 for i in graph}
	d[s] = 0
	while len(q) > 0:
		v = heappop(q)[1]
		count += 1
		for w in graph[v]:
			if d[w[0]] > d[v] + w[1] or d[w[0]] == -1:
				d[w[0]] = d[v] + w[1]
				heappush(q, (d[w[0]], w[0]))
	return d

def main():
	(n, m) = map(int, sys.stdin.readline().split())
	(sx, sy, fx, fy) = map(int, sys.stdin.readline().split())
	s = (sx, sy)
	graph = read_graph(s, n, m)
	d = dijkstra(graph, s)
	m = -1
	for i in graph:
		if m == -1:
			m = d[i] + abs(fx - i[0]) + abs(fy - i[1])
			continue
		m = min(m, d[i] + abs(fx - i[0]) + abs(fy - i[1]))
	print(m)
main()


from sys import stdin
input = stdin.readline
import heapq

def solve():
	INF = 10 ** 10 + 10
	(n, k) = map(int, input().split())
	(sy, sx, ey, ex) = map(int, input().split())
	p = [tuple(map(int, inp.split())) for inp in stdin.read().splitlines()]

	def dis2(a, b):
		return min(abs(a[0] - b[0]), abs(a[1] - b[1]))

	def dis1(a, b):
		return abs(a[0] - b[0]) + abs(a[1] - b[1])
	start = [sy, sx]
	end = [ey, ex]
	if k == 0:
		print(dis1(start, end))
		return
	adj = [[] for _ in range(k + 2)]
	dis = [INF] * (k + 2)
	temp = [(x, y, i) for (i, (x, y)) in enumerate(p)]
	xorder = sorted(temp, key=lambda x: x[0])
	yorder = sorted(temp, key=lambda x: x[1])
	for ((px, py, pi), (x, y, i)) in zip(xorder, xorder[1:]):
		d = min(x - px, abs(py - y))
		adj[pi + 1].append([i + 1, d])
		adj[i + 1].append([pi + 1, d])
	for ((px, py, pi), (x, y, i)) in zip(yorder, yorder[1:]):
		d = min(abs(x - px), y - py)
		adj[pi + 1].append([i + 1, d])
		adj[i + 1].append([pi + 1, d])
	res = dis1(start, end)
	for i in range(k):
		adj[0].append([i + 1, dis2(start, p[i])])
		adj[i + 1].append([k + 1, dis1(p[i], end)])
	h = [(0, 0)]
	dis[0] = 0
	while h:
		(d, cur) = heapq.heappop(h)
		if d > dis[cur]:
			continue
		for (nxt, dd) in adj[cur]:
			nd = d + dd
			if nd < dis[nxt]:
				dis[nxt] = nd
				heapq.heappush(h, (nd, nxt))
	print(min(res, dis[k + 1]))
solve()


from heapq import *
INF = float('inf')

def dit(xx, yy, x, y):
	return abs(xx - x) + abs(yy - y)
(n, m) = map(int, input().split())
(xi, yi, xt, yt) = map(int, input().split())
s = [xi, yi]
f = [xt, yt]
grapx = [(xi, 0)]
grapy = [(yi, 0)]
adj = [[] for _ in range(m + 1)]
adj[0].append((dit(xi, yi, xt, yt), m + 1))
for i in range(1, m + 1):
	(x, y) = map(int, input().split())
	heappush(grapx, (x, i))
	heappush(grapy, (y, i))
	adj[i].append((dit(xt, yt, x, y), m + 1))
for i in range(2):
	graph = grapy if i else grapx
	prev = heappop(graph)
	while graph:
		curr = heappop(graph)
		d = abs(curr[0] - prev[0])
		adj[prev[1]].append((d, curr[1]))
		adj[curr[1]].append((d, prev[1]))
		prev = curr
D = [INF for _ in range(m + 2)]
D[0] = 0
hq = [(0, 0)]
while hq:
	(dcur, nd) = heappop(hq)
	if nd == m + 1:
		continue
	if D[nd] < dcur:
		continue
	for (dnx, nx) in adj[nd]:
		if D[nx] > dcur + dnx:
			D[nx] = dcur + dnx
			heappush(hq, (D[nx], nx))
print(D[m + 1])


from heapq import heappush, heappop
from math import inf
import sys
input = sys.stdin.buffer.readline

def dist(a, b):
	return min(abs(a[0] - b[0]), abs(a[1] - b[1]))

def add(vertices, adj, m):
	for i in range(m - 1):
		adj[vertices[i][2]].append([vertices[i + 1][2], dist(vertices[i], vertices[i + 1])])
		adj[vertices[i + 1][2]].append([vertices[i][2], dist(vertices[i], vertices[i + 1])])

def prog():
	(n, m) = map(int, input().split())
	m += 1
	(sx, sy, ex, ey) = map(int, input().split())
	adj = [[] for i in range(m)]
	vertices = [[sx, sy, 0]]
	for i in range(1, m):
		(x, y) = map(int, input().split())
		vertices.append([x, y, i])
	final_dist = [0] * m
	for i in range(m):
		final_dist[i] = abs(ex - vertices[i][0]) + abs(ey - vertices[i][1])
	vertices.sort()
	add(vertices, adj, m)
	vertices.sort(key=lambda x: x[1])
	add(vertices, adj, m)
	to_dists = [inf] * m
	heap = [(0, 0)]
	while heap:
		curr = heappop(heap)
		if to_dists[curr[1]] > curr[0]:
			to_dists[curr[1]] = curr[0]
			for neighbor in adj[curr[1]]:
				heappush(heap, (curr[0] + neighbor[1], neighbor[0]))
	shortest_time = abs(ex - sx) + abs(ey - sy)
	for i in range(m):
		shortest_time = min(shortest_time, to_dists[i] + final_dist[i])
	print(shortest_time)
prog()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())

def get_dis(x, y, fx, fy):
	return abs(fx - x) + abs(fy - y)

def ins_dis(x, y, fx, fy):
	return min(abs(fx - x), abs(fy - y))
edge = [[] for i in range(m + 2)]
ps = []
for i in range(m):
	(x, y) = map(int, input().split())
	ps.append((i + 1, x, y))
	edge[0].append((i + 1, ins_dis(sx, sy, x, y)))
	edge[i + 1].append((m + 1, get_dis(fx, fy, x, y)))
ps.sort(key=lambda a: a[1])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][1] - ps[i - 1][1]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][1] - ps[i][1]))
ps.sort(key=lambda a: a[2])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][2] - ps[i - 1][2]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][2] - ps[i][2]))
from heapq import *
q = [(0, 0)]
inf = int(1e+19)
dis = [inf for i in range(m + 2)]
s = [False for i in range(m + 2)]
while q:
	(curdis, cur) = heappop(q)
	if not s[cur]:
		s[cur] = True
		for (nex, d) in edge[cur]:
			if curdis + d < dis[nex]:
				dis[nex] = curdis + d
				heappush(q, (curdis + d, nex))
print(min(dis[-1], get_dis(sx, sy, fx, fy)))


from heapq import heappop, heappush

def ip_dis(x, y, k, l):
	return min(abs(k - x), abs(l - y))

def fp_dis(x, y, k, l):
	return abs(k - x) + abs(l - y)
inf = 10 ** 10
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
G = [[] for _ in range(m + 2)]
ps = []
for i in range(1, m + 1):
	(x, y) = map(int, input().split())
	ps.append((i, x, y))
	G[0].append((i, ip_dis(sx, sy, x, y)))
	G[i].append((m + 1, fp_dis(x, y, fx, fy)))
ps.sort(key=lambda x: x[1])
for i in range(m - 1):
	d = ps[i + 1][1] - ps[i][1]
	G[ps[i][0]].append((ps[i + 1][0], d))
	G[ps[i + 1][0]].append((ps[i][0], d))
ps.sort(key=lambda x: x[2])
for i in range(m - 1):
	d = ps[i + 1][2] - ps[i][2]
	G[ps[i][0]].append((ps[i + 1][0], d))
	G[ps[i + 1][0]].append((ps[i][0], d))
G[0].append((m + 1, fp_dis(sx, sy, fx, fy)))
res = {i: inf for i in range(m + 2)}
visited = {i: True for i in range(m + 2)}
q = [(0, 0)]
while q:
	(d, v) = heappop(q)
	if visited[v]:
		visited[v] = False
		for (u, l) in G[v]:
			if l + d < res[u]:
				res[u] = l + d
				heappush(q, (res[u], u))
print(res[m + 1])


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))
ilelec = lambda : map(int1, input().split())
alelec = lambda : list(map(int1, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]
MOD = 1000000000 + 7

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
(n, m) = ilele()
(sx, sy, fx, fy) = alele()

def get_dis(x, y, fx, fy):
	return abs(fx - x) + abs(fy - y)

def ins_dis(x, y, fx, fy):
	return min(abs(fx - x), abs(fy - y))
edge = [[] for i in range(m + 2)]
ps = []
for i in range(m):
	(x, y) = ilele()
	ps.append((i + 1, x, y))
	edge[0].append((i + 1, ins_dis(sx, sy, x, y)))
	edge[i + 1].append((m + 1, get_dis(fx, fy, x, y)))
ps.sort(key=lambda a: a[1])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][1] - ps[i - 1][1]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][1] - ps[i][1]))
ps.sort(key=lambda a: a[2])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][2] - ps[i - 1][2]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][2] - ps[i][2]))
q = [(0, 0)]
inf = float('inf')
dis = [inf for i in range(m + 2)]
s = [False for i in range(m + 2)]
while q:
	(curdis, cur) = heapq.heappop(q)
	if not s[cur]:
		s[cur] = True
		for (nex, d) in edge[cur]:
			if curdis + d < dis[nex]:
				dis[nex] = curdis + d
				heapq.heappush(q, (curdis + d, nex))
print(min(dis[-1], get_dis(sx, sy, fx, fy)))


import sys
from heapq import heapify, heappush, heappop
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
v = []
graph = [[] for _ in range(m + 1)]
mapVert = {}
inverseMapVert = {}
for i in range(m):
	(a, b) = map(int, input().split())
	v.append((a, b))
	mapVert[a, b] = i + 1
	inverseMapVert[i + 1] = (a, b)
v.sort()
for i in range(m - 1):
	a = mapVert[v[i]]
	b = mapVert[v[i + 1]]
	(x1, y1) = v[i]
	(x2, y2) = v[i + 1]
	diffx = abs(x1 - x2)
	diffy = abs(y1 - y2)
	if diffx <= diffy:
		graph[a].append((b, diffx))
		graph[b].append((a, diffx))
for i in range(len(v)):
	(a, b) = v[i]
	v[i] = (b, a)
v.sort()
for i in range(len(v)):
	(a, b) = v[i]
	v[i] = (b, a)
for i in range(m - 1):
	a = mapVert[v[i]]
	b = mapVert[v[i + 1]]
	(x1, y1) = v[i]
	(x2, y2) = v[i + 1]
	diffx = abs(x1 - x2)
	diffy = abs(y1 - y2)
	if diffy < diffx:
		graph[a].append((b, diffy))
		graph[b].append((a, diffy))
for i in inverseMapVert:
	(x, y) = inverseMapVert[i]
	w = min(abs(sx - x), abs(sy - y))
	graph[0].append((i, w))
	graph[i].append((0, w))
mapVert[sx, sy] = 0
inverseMapVert[0] = (sx, sy)
d = [1e+18] * (m + 1)
d[0] = 0
heap = []
heapify(heap)
heappush(heap, (0, 0))
while len(heap) > 0:
	(w, u) = heappop(heap)
	if w > d[u]:
		continue
	for (v, w1) in graph[u]:
		if d[u] + w1 < d[v]:
			d[v] = d[u] + w1
			heappush(heap, (d[v], v))
minx = 1e+18
for i in range(m + 1):
	(x, y) = inverseMapVert[i]
	minx = min(minx, d[i] + abs(fx - x) + abs(fy - y))
print(minx)


import sys
from array import array
import typing as Tp

def input():
	return sys.stdin.buffer.readline().decode('utf-8')

def output(*args):
	sys.stdout.buffer.write(('\n'.join(map(str, args)) + '\n').encode('utf-8'))

def main():
	from heapq import heappop, heappush
	from operator import itemgetter
	(n, m) = map(int, input().split())
	(sx, sy, fx, fy) = map(int, input().split())
	points: Tp.List[Tp.Tuple[int, int, int]] = [(sx, sy, 0)] + [(x, y, i) for (i, (x, y)) in enumerate((map(int, input().split()) for _ in range(m)), start=1)]
	adj = [[] for _ in range(m + 1)]
	for axis in range(2):
		points.sort(key=itemgetter(axis))
		for i in range(m):
			(u, v, w) = (points[i][2], points[i + 1][2], points[i + 1][axis] - points[i][axis])
			adj[u].append((v, w))
			adj[v].append((u, w))
	points.sort(key=itemgetter(2))
	dp = [0] + [2 * 10 ** 9] * m
	ans = 2 * 10 ** 9
	hq = [(0, 0)]
	while hq:
		(cost, v) = heappop(hq)
		if dp[v] < cost:
			continue
		ans = min(ans, cost + abs(points[v][0] - fx) + abs(points[v][1] - fy))
		for (dest, w) in adj[v]:
			if dp[dest] <= cost + w:
				continue
			dp[dest] = cost + w
			heappush(hq, (cost + w, dest))
	print(ans)
main()


import os, io, heapq
INF = 10 ** 10
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
graph1 = []
for i in range(m):
	(x, y) = map(int, input().split())
	graph1.append([x, y, i])
xorder = sorted(graph1, key=lambda student: student[0])
yorder = sorted(graph1, key=lambda student: student[1])
graph = [[] for i in range(m)]
for i in range(m - 1):
	graph[xorder[i][2]].append([xorder[i + 1][2], xorder[i + 1][0] - xorder[i][0]])
	graph[xorder[i + 1][2]].append([xorder[i][2], xorder[i + 1][0] - xorder[i][0]])
	graph[yorder[i][2]].append([yorder[i + 1][2], yorder[i + 1][1] - yorder[i][1]])
	graph[yorder[i + 1][2]].append([yorder[i][2], yorder[i + 1][1] - yorder[i][1]])
dist = [INF] * len(graph)
queue = []
for i in range(m):
	heapq.heappush(queue, (min(abs(graph1[i][0] - sx), abs(graph1[i][1] - sy)), i))
while queue:
	(path_len, v) = heapq.heappop(queue)
	if dist[v] == INF:
		dist[v] = path_len
		for w in graph[v]:
			if dist[w[0]] == INF:
				heapq.heappush(queue, (dist[v] + w[1], w[0]))
ans = abs(fx - sx) + abs(fy - sy)
for i in range(m):
	ans = min(ans, dist[i] + abs(fx - graph1[i][0]) + abs(fy - graph1[i][1]))
print(ans)


import math
from sys import stdin, stdout

def getInts():
	return list(map(int, stdin.readline().strip().split()))

def getInt():
	return int(stdin.readline().strip())

def lower_bound(v, x):
	low = 0
	high = len(v) - 1
	ans = len(v)
	while low <= high:
		mid = (low + high) // 2
		if v[mid] < x:
			low = mid + 1
		else:
			ans = mid
			high = mid - 1
	return ans

def upper_bound(v, x):
	low = 0
	high = len(v) - 1
	ans = len(v)
	while low <= high:
		mid = (low + high) // 2
		if v[mid] <= x:
			low = mid + 1
		else:
			ans = mid
			high = mid - 1
	return ans
MOD = 1000000007

def mul(x, y):
	ans = x * y
	if ans > MOD:
		ans = ans % MOD
	if ans < 0:
		ans = ans % MOD
		ans = (ans + MOD) % MOD
	return ans

def add(x, y):
	ans = x + y
	if ans > MOD:
		ans = ans % MOD
	if ans < 0:
		ans = ans % MOD
		ans = (ans + MOD) % MOD
	return ans
import bisect

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
(n, m) = getInts()
(sx, sy, fx, fy) = getInts()
x = [0] * m
y = [0] * m
X = []
Y = []
for i in range(m):
	(x[i], y[i]) = getInts()
	X.append((x[i], i + 1))
	Y.append((y[i], i + 1))
X.sort()
Y.sort()
graphs = [[] for i in range(m + 2)]
for i in range(m - 1):
	(x1, j) = X[i]
	(x2, k) = X[i + 1]
	graphs[j].append((x2 - x1, k))
	graphs[k].append((x2 - x1, j))
for i in range(m - 1):
	(y1, j) = Y[i]
	(y2, k) = Y[i + 1]
	graphs[j].append((y2 - y1, k))
	graphs[k].append((y2 - y1, j))
for i in range(m):
	graphs[0].append((min(abs(x[i] - sx), abs(y[i] - sy)), i + 1))
	graphs[i + 1].append((abs(x[i] - fx) + abs(y[i] - fy), m + 1))
graphs[0].append((abs(sx - fx) + abs(sy - fy), m + 1))
import heapq
INF = 10 ** 18

def dijkishtra(graphs, n):
	dis = [INF] * n
	visited = [False] * n
	edgelist = []
	heapq.heappush(edgelist, (0, 0))
	dis[0] = 0
	while len(edgelist):
		edge = heapq.heappop(edgelist)
		if visited[edge[1]] == True:
			continue
		ver = edge[1]
		visited[ver] = True
		for e in graphs[ver]:
			if dis[e[1]] > edge[0] + e[0]:
				dis[e[1]] = edge[0] + e[0]
				heapq.heappush(edgelist, (dis[e[1]], e[1]))
	return dis[n - 1]
d = dijkishtra(graphs, m + 2)
if m == 0:
	stdout.write(str(abs(sx - fx) + abs(sy - fy)))
else:
	stdout.write(str(d))


import sys
import io, os
input = sys.stdin.buffer.readline
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
XY = []
X = []
Y = []
for i in range(m):
	(x, y) = map(int, input().split())
	XY.append((x, y))
	X.append((x, i))
	Y.append((y, i))
if m == 0:
	print(abs(sx - fx) + abs(sy - fy))
	exit()
X.sort()
Y.sort()
g = [[] for _ in range(m + 2)]
for i in range(m - 1):
	(xj, j) = X[i]
	(xk, k) = X[i + 1]
	g[j + 1].append((xk - xj, k + 1))
	g[k + 1].append((xk - xj, j + 1))
for i in range(m - 1):
	(yj, j) = Y[i]
	(yk, k) = Y[i + 1]
	g[j + 1].append((yk - yj, k + 1))
	g[k + 1].append((yk - yj, j + 1))
for i in range(m):
	(x, y) = XY[i]
	d = min(abs(x - sx), abs(y - sy))
	g[0].append((d, i + 1))
for i in range(m):
	(x, y) = XY[i]
	d = abs(x - fx) + abs(y - fy)
	g[i + 1].append((d, m + 1))
d = abs(sx - fx) + abs(sy - fy)
g[0].append((d, m + 1))
import heapq
INF = 10 ** 18

def dijkstra_heap(s, edge, n):
	d = [INF] * n
	used = [True] * n
	d[s] = 0
	used[s] = False
	edgelist = []
	for e in edge[s]:
		heapq.heappush(edgelist, e)
	while len(edgelist):
		minedge = heapq.heappop(edgelist)
		if not used[minedge[1]]:
			continue
		v = minedge[1]
		d[v] = minedge[0]
		used[v] = False
		for e in edge[v]:
			if used[e[1]]:
				heapq.heappush(edgelist, (e[0] + d[v], e[1]))
	return d
d = dijkstra_heap(0, g, m + 2)
print(d[m + 1])


from heapq import heappop, heappush
import sys
input = sys.stdin.readline
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
(p, a, b) = ([], [], [])
for i in range(m):
	(x, y) = map(int, input().split())
	p.append((x, y))
	a.append((x, y, i))
	b.append((y, x, i))
e = [[] for _ in range(m)]
a.sort()
for i in range(1, m):
	(x1, y1, u) = a[i - 1]
	(x2, y2, v) = a[i]
	d = min(abs(x1 - x2), abs(y1 - y2))
	e[u].append((v, d))
	e[v].append((u, d))
b.sort()
for i in range(1, m):
	(x1, y1, u) = b[i - 1]
	(x2, y2, v) = b[i]
	d = min(abs(x1 - x2), abs(y1 - y2))
	e[u].append((v, d))
	e[v].append((u, d))
hp = []
d = [0] * m
for i in range(m):
	d[i] = min(abs(sx - p[i][0]), abs(sy - p[i][1]))
	heappush(hp, (d[i], i))
while hp:
	(w, x) = heappop(hp)
	if d[x] != w:
		continue
	for (y, c) in e[x]:
		if d[y] > w + c:
			d[y] = w + c
			heappush(hp, (d[y], y))
ans = abs(sx - fx) + abs(sy - fy)
for i in range(m):
	ans = min(ans, d[i] + abs(fx - p[i][0]) + abs(fy - p[i][1]))
print(ans)


import heapq
import sys
input = sys.stdin.readline
INF = 10 ** 12

def Dijkstra(graph, start):
	dist = [INF] * len(graph)
	parent = [INF] * len(graph)
	queue = [(0, start)]
	while queue:
		(path_len, v) = heapq.heappop(queue)
		if dist[v] == INF:
			dist[v] = path_len
			for w in graph[v]:
				if dist[w[0]] == INF:
					parent[w[0]] = v
					heapq.heappush(queue, (dist[v] + w[1], w[0]))
	return (dist, parent)
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
if m == 0:
	print(abs(sx - fx) + abs(sy - fy))
	exit()
x = []
y = []
graph = [[] for i in range(m + 1)]
sorted_by_x = []
sorted_by_y = []
for i in range(m):
	(tx, ty) = map(int, input().split())
	x.append(tx)
	y.append(ty)
	sorted_by_x.append([tx, i])
	sorted_by_y.append([ty, i])
	graph[i].append([m, abs(fx - tx) + abs(fy - ty)])
	graph[m].append([i, abs(fx - tx) + abs(fy - ty)])
sorted_by_x = sorted(sorted_by_x, key=lambda thing: thing[0])
sorted_by_y = sorted(sorted_by_y, key=lambda thing: thing[0])
for i in range(m - 1):
	(x1, ind1) = sorted_by_x[i]
	(x2, ind2) = sorted_by_x[i + 1]
	graph[ind1].append([ind2, abs(x1 - x2)])
	graph[ind2].append([ind1, abs(x1 - x2)])
for i in range(m - 1):
	(y1, ind1) = sorted_by_y[i]
	(y2, ind2) = sorted_by_y[i + 1]
	graph[ind1].append([ind2, abs(y1 - y2)])
	graph[ind2].append([ind1, abs(y1 - y2)])
(dist, parent) = Dijkstra(graph, m)
answer = INF
for i in range(m):
	total_dist = min(abs(sx - x[i]), abs(sy - y[i])) + dist[i]
	if answer > total_dist:
		answer = total_dist
if answer > abs(sx - fx) + abs(sy - fy):
	answer = abs(sx - fx) + abs(sy - fy)
print(answer)


import sys
input = sys.stdin.readline
import heapq
from operator import itemgetter
(n, m) = list(map(int, input().split()))
(sx, sy, fx, fy) = list(map(int, input().split()))
W = [list(map(int, input().split())) + [i] for i in range(m)] + [[sx, sy, m]]
ANS = [n ** 2]

def ans(time, x, y):
	ANS[0] = min(ANS[0], time + abs(fx - x) + abs(fy - y))
WX = sorted(W, key=itemgetter(0))
WY = sorted(W, key=itemgetter(1))
EDGE = [[] for i in range(m + 1)]
TIME = [1 << 60] * (m + 1)
TIME[m] = 0
for i in range(1, m + 1):
	(x0, y0, m0) = WX[i - 1]
	(x1, y1, m1) = WX[i]
	EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1))))
	EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1))))
	(x0, y0, m0) = WY[i - 1]
	(x1, y1, m1) = WY[i]
	EDGE[m0].append((m1, min(abs(x0 - x1), abs(y0 - y1))))
	EDGE[m1].append((m0, min(abs(x0 - x1), abs(y0 - y1))))
Q = [(0, m)]
while Q:
	(time, town) = heapq.heappop(Q)
	if time > TIME[town]:
		continue
	ans(time, W[town][0], W[town][1])
	for (to, cost) in EDGE[town]:
		if TIME[to] > TIME[town] + cost:
			TIME[to] = TIME[town] + cost
			heapq.heappush(Q, (TIME[to], to))
print(ANS[0])


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(RL())

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return min(abs(x1 - x2), abs(y1 - y2))

def toord(c):
	return ord(c) - ord('a')

def lcm(a, b):
	return a * b // gcd(a, b)
mod = 10 ** 9 + 7
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	(n, m) = RL()
	(sx, sy, fx, fy) = RL()
	arr = [RLL() + [i] for i in range(m)] + [[sx, sy, m]]
	sort_x = sorted(arr, key=lambda a: a[0])
	sort_y = sorted(arr, key=lambda a: a[1])
	gp = [[] for _ in range(m + 1)]
	for i in range(1, m + 1):
		(a1, b1, n1) = sort_x[i - 1]
		(a2, b2, n2) = sort_x[i]
		dis = mdis(a1, b1, a2, b2)
		gp[n1].append((n2, dis))
		gp[n2].append((n1, dis))
		(a1, b1, n1) = sort_y[i - 1]
		(a2, b2, n2) = sort_y[i]
		dis = mdis(a1, b1, a2, b2)
		gp[n1].append((n2, dis))
		gp[n2].append((n1, dis))
	ans = [10 ** 10] * (m + 1)
	Q = [(0, m)]
	while Q:
		(dis, num) = heappop(Q)
		ans[num] = min(ans[num], dis)
		for (nd, dis_nex) in gp[num]:
			if ans[num] + dis_nex < ans[nd]:
				tol_dis = dis_nex + ans[num]
				ans[nd] = min(ans[nd], tol_dis)
				heappush(Q, (ans[nd], nd))
	res = abs(fx - sx) + abs(fy - sy)
	for i in range(m + 1):
		(dis, nd) = (ans[i], i)
		(x, y, _) = arr[nd]
		now = dis + abs(x - fx) + abs(y - fy)
		res = min(res, now)
	print(res)
main()


(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())

def get_dis(x, y, fx, fy):
	return abs(fx - x) + abs(fy - y)

def ins_dis(x, y, fx, fy):
	return min(abs(fx - x), abs(fy - y))
edge = [[] for i in range(m + 2)]
ps = []
for i in range(m):
	(x, y) = map(int, input().split())
	ps.append((i + 1, x, y))
	edge[0].append((i + 1, ins_dis(sx, sy, x, y)))
	edge[i + 1].append((m + 1, get_dis(fx, fy, x, y)))
ps.sort(key=lambda a: a[1])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][1] - ps[i - 1][1]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][1] - ps[i][1]))
ps.sort(key=lambda a: a[2])
for i in range(len(ps)):
	if i > 0:
		edge[ps[i][0]].append((ps[i - 1][0], ps[i][2] - ps[i - 1][2]))
	if i < len(ps) - 1:
		edge[ps[i][0]].append((ps[i + 1][0], ps[i + 1][2] - ps[i][2]))
from heapq import *
q = [(0, 0)]
inf = int(1e+19)
dis = [inf for i in range(m + 2)]
s = [False for i in range(m + 2)]
while q:
	(curdis, cur) = heappop(q)
	if not s[cur]:
		s[cur] = True
		for (nex, d) in edge[cur]:
			if curdis + d < dis[nex]:
				dis[nex] = curdis + d
				heappush(q, (curdis + d, nex))
print(min(dis[-1], get_dis(sx, sy, fx, fy)))


import sys
from sys import stdin
(n, m) = map(int, stdin.readline().split())
(sx, sy, gx, gy) = map(int, stdin.readline().split())
xdic = {}
xlis = []
ydic = {}
ylis = []
if sx not in xdic:
	xdic[sx] = 0
	xlis.append(sx)
if sy not in ydic:
	ydic[sy] = 0
	ylis.append(sy)
xy = []
for i in range(m):
	(x, y) = map(int, stdin.readline().split())
	if x not in xdic:
		xdic[x] = 0
		xlis.append(x)
	if y not in ydic:
		ydic[y] = 0
		ylis.append(y)
	xy.append((x, y))
xlis.sort()
ylis.sort()
for i in range(len(xlis)):
	xdic[xlis[i]] = m + i
for i in range(len(ylis)):
	ydic[ylis[i]] = m + len(xlis) + i
lis = [[] for i in range(m + len(xlis) + len(ylis))]
for i in range(len(xlis) - 1):
	lis[m + i].append((m + i + 1, xlis[i + 1] - xlis[i]))
	lis[m + i + 1].append((m + i, xlis[i + 1] - xlis[i]))
for i in range(len(ylis) - 1):
	lis[m + len(xlis) + i].append((m + len(xlis) + i + 1, ylis[i + 1] - ylis[i]))
	lis[m + len(xlis) + i + 1].append((m + len(xlis) + i, ylis[i + 1] - ylis[i]))
for i in range(m):
	(x, y) = xy[i]
	lis[i].append((xdic[x], 0))
	lis[xdic[x]].append((i, 0))
	lis[i].append((ydic[y], 0))
	lis[ydic[y]].append((i, 0))
ans = abs(sx - gx) + abs(sy - gy)
import heapq
if True:
	d = ret = [float('inf')] * len(lis)
	d[xdic[sx]] = 0
	d[ydic[sy]] = 0
	q = [(0, xdic[sx])]
	heapq.heappush(q, (0, ydic[sy]))
	while len(q) > 0:
		(ncost, now) = heapq.heappop(q)
		if ncost != ret[now]:
			continue
		for (nex, ecost) in lis[now]:
			if ret[nex] > ncost + ecost:
				ret[nex] = ncost + ecost
				heapq.heappush(q, (ret[nex], nex))
for i in range(m):
	(x, y) = xy[i]
	ans = min(ans, d[i] + abs(x - gx) + abs(y - gy))
print(ans)


import sys, math
import io, os
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write('\n'.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = 10 ** 9 + 7

def dijkstra(n, graph, start):
	dist = [float('inf')] * n
	dist[start] = 0
	ans = INF
	queue = [(0, start)]
	while queue:
		(path_len, v) = heappop(queue)
		if path_len == dist[v]:
			for (w, edge_len) in graph[v]:
				if edge_len + path_len < dist[w]:
					dist[w] = edge_len + path_len
					heappush(queue, (edge_len + path_len, w))
			ans = min(ans, dist[v] + abs(l[v][0] - fx) + abs(l[v][1] - fy))
	return ans
(n, m) = mdata()
(sx, sy, fx, fy) = mdata()
l = [mdata() + [i] for i in range(m)] + [[sx, sy, m]]
dis = [INF] * (m + 1)
graph = [[] for i in range(m + 1)]
X = sorted(l, key=lambda x: x[0])
Y = sorted(l, key=lambda x: x[1])
for i in range(1, m + 1):
	(x1, y1, ind1) = X[i - 1]
	(x2, y2, ind2) = X[i]
	graph[ind1].append([ind2, min(abs(x1 - x2), abs(y1 - y2))])
	graph[ind2].append([ind1, min(abs(x1 - x2), abs(y1 - y2))])
	(x1, y1, ind1) = Y[i - 1]
	(x2, y2, ind2) = Y[i]
	graph[ind1].append([ind2, min(abs(x1 - x2), abs(y1 - y2))])
	graph[ind2].append([ind1, min(abs(x1 - x2), abs(y1 - y2))])
out(dijkstra(m + 1, graph, m))


from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		for v in graph[u]:
			if v not in d or d[v] > d[u] + graph[u][v]:
				d[v] = d[u] + graph[u][v]
				heappush(heap, (d[v], v))
	return d
(n, m) = map(int, input().split())
(sx, sy, fx, fy) = map(int, input().split())
s = set()
for i in range(m):
	(x, y) = map(int, input().split())
	s.add((x, y))
graph = defaultdict(dict)
s.add((sx, sy))
arr = list(s)
for (i, (x, y)) in enumerate(arr):
	if x == sx and y == sy:
		start = i
l = len(arr)
ax = sorted(range(l), key=lambda i: arr[i][0])
ay = sorted(range(l), key=lambda i: arr[i][1])
for i in range(l - 1):
	tmp = arr[ax[i + 1]][0] - arr[ax[i]][0]
	if ax[i + 1] not in graph[ax[i]]:
		graph[ax[i]][ax[i + 1]] = graph[ax[i + 1]][ax[i]] = tmp
	else:
		graph[ax[i]][ax[i + 1]] = graph[ax[i + 1]][ax[i]] = min(tmp, graph[ax[i]][ax[i + 1]])
for i in range(l - 1):
	tmp = arr[ay[i + 1]][1] - arr[ay[i]][1]
	if ay[i + 1] not in graph[ay[i]]:
		graph[ay[i]][ay[i + 1]] = graph[ay[i + 1]][ay[i]] = tmp
	else:
		graph[ay[i]][ay[i + 1]] = graph[ay[i + 1]][ay[i]] = min(tmp, graph[ay[i]][ay[i + 1]])
d = dij(start, graph)
ans = inf
for k in d:
	(x, y) = arr[k]
	ans = min(ans, abs(x - fx) + abs(y - fy) + d[k])
print(ans)


import sys, heapq
input = sys.stdin.buffer.readline

def main():
	dg = 10 ** 10
	(n, m) = map(int, input().split())
	(sx, sy, fx, fy) = map(int, input().split())
	s = sx * dg + sy
	f = fx * dg + fy
	xy = []
	yx = []
	xy.append(s)
	yx.append(sy * dg + sx)
	for i in range(m):
		(x, y) = map(int, input().split())
		xy.append(x * dg + y)
		yx.append(y * dg + x)
	d = [-1] * (m + 2)
	xy.sort()
	yx.sort()
	edge = [[] for i in range(m + 2)]
	bx = sx
	by = sy
	tank = []
	dic = dict()
	for i in range(m + 1):
		dic[xy[i]] = i + 1
		(bx, by) = divmod(xy[i], dg)
		c = abs(fx - bx) + abs(fy - by)
		edge[0].append(c * dg + i + 1)
		edge[i + 1].append(c * dg)
	bx = sx
	by = sy
	bidx = dic[s]
	for e in xy:
		(nx, ny) = divmod(e, dg)
		nidx = dic[nx * dg + ny]
		c = min(abs(nx - bx), abs(ny - by))
		edge[nidx].append(c * dg + bidx)
		edge[bidx].append(c * dg + nidx)
		(bidx, bx, by) = (nidx, nx, ny)
	bx = sx
	by = sy
	bidx = dic[s]
	for e in yx:
		(ny, nx) = divmod(e, dg)
		nidx = dic[nx * dg + ny]
		c = min(abs(nx - bx), abs(ny - by))
		edge[nidx].append(c * dg + bidx)
		edge[bidx].append(c * dg + nidx)
		(bidx, bx, by) = (nidx, nx, ny)
	for e in edge[dic[s]]:
		heapq.heappush(tank, e)
	d[dic[s]] = 0
	used = [True] * (m + 2)
	d[dic[s]] = False
	while tank:
		q = heapq.heappop(tank)
		(c, now) = divmod(q, dg)
		if not used[now]:
			continue
		d[now] = c
		used[now] = False
		if now == 0:
			break
		for e in edge[now]:
			(cost, nxt) = divmod(e, dg)
			if used[nxt]:
				heapq.heappush(tank, e + c * dg)
	ans = abs(sx - fx) + abs(sy - fy)
	if d[0] == -1:
		print(ans)
	else:
		print(min(d[0], ans))
main()


import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def MI1():
	return map(int1, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LI1():
	return list(map(int1, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def LLI1(rows_number):
	return [LI1() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline()[:-1]

def SI():
	return sys.stdin.buffer.readline()[:-1].decode()
from heapq import *
inf = 10 ** 16
(n, m) = MI()
(sx, sy, gx, gy) = MI1()
xy = LLI1(m)
(xx, yy) = (set(), set())
for (x, y) in xy:
	xx.add(x)
	yy.add(y)
dec_x = list(sorted(xx))
enc_x = {x: i for (i, x) in enumerate(dec_x)}
dec_y = list(sorted(yy))
enc_y = {x: i for (i, x) in enumerate(dec_y)}
(xn, yn) = (len(xx), len(yy))
to = [[] for _ in range(xn + yn)]
for u in range(xn - 1):
	d = dec_x[u + 1] - dec_x[u]
	to[u].append((u + 1, d))
	to[u + 1].append((u, d))
for u in range(yn - 1):
	d = dec_y[u + 1] - dec_y[u]
	u += xn
	to[u].append((u + 1, d))
	to[u + 1].append((u, d))
for (x, y) in xy:
	d = min(abs(x - sx), abs(y - sy))
	(x, y) = (enc_x[x], enc_y[y])
	y += xn
	to[x].append((y, 0))
	to[y].append((x, 0))
	to[x].append((xn + yn, d))
hp = []
dist = [inf] * (xn + yn + 1)
for (u, (x, y)) in enumerate(xy):
	d = abs(gx - x) + abs(gy - y)
	x = enc_x[x]
	if dist[x] <= d:
		continue
	dist[x] = d
	heappush(hp, (d, x))
ans = abs(sx - gx) + abs(sy - gy)
while hp:
	(d, u) = heappop(hp)
	if d > ans or u == xn + yn:
		ans = min(ans, d)
		break
	if d > dist[u]:
		continue
	dist[u] = d
	for (v, c) in to[u]:
		if dist[v] <= d + c:
			continue
		dist[v] = d + c
		heappush(hp, (d + c, v))
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def print_list(l):
	print(' '.join(map(str, l)))
from heapq import *
from collections import defaultdict as dc
inf = 3 * 10 ** 9
(n, m) = RL()
(sx, sy, gx, gy) = RL()
xy = [RLL() for _ in range(m)]
(xx, yy) = (set((a[0] for a in xy)), set((a[1] for a in xy)))
dec_x = list(sorted(xx))
enc_x = {x: i for (i, x) in enumerate(dec_x)}
dec_y = list(sorted(yy))
enc_y = {x: i for (i, x) in enumerate(dec_y)}
(xn, yn) = (len(xx), len(yy))
to = [[] for _ in range(xn + yn)]
for u in range(xn - 1):
	d = dec_x[u + 1] - dec_x[u]
	to[u].append((u + 1, d))
	to[u + 1].append((u, d))
for u in range(yn - 1):
	d = dec_y[u + 1] - dec_y[u]
	u += xn
	to[u].append((u + 1, d))
	to[u + 1].append((u, d))
for (x, y) in xy:
	d = min(abs(x - sx), abs(y - sy))
	(x, y) = (enc_x[x], enc_y[y])
	y += xn
	to[x].append((y, 0))
	to[y].append((x, 0))
	to[x].append((xn + yn, d))
hp = []
dist = [inf] * (xn + yn + 1)
for (u, (x, y)) in enumerate(xy):
	d = abs(gx - x) + abs(gy - y)
	x = enc_x[x]
	if dist[x] <= d:
		continue
	dist[x] = d
	heappush(hp, (d, x))
ans = abs(sx - gx) + abs(sy - gy)
while hp:
	(d, u) = heappop(hp)
	if d > ans or u == xn + yn:
		ans = min(ans, d)
		break
	if d > dist[u]:
		continue
	dist[u] = d
	for (v, c) in to[u]:
		if dist[v] <= d + c:
			continue
		dist[v] = d + c
		heappush(hp, (d + c, v))
print(ans)