import sys from collections import defaultdict from heapq import heapify, heappush, heappop input = lambda: sys.stdin.readline().rstrip() inf = float('inf') def dijkstra(G: list, s: int) -> list: "Return dist from s. / O(|E|log|V|)" dist = defaultdict(lambda: inf) dist[s] = 0 hq = [(0, s)] while hq: d, v = heappop(hq) if dist[v] < d: continue for x,c in G[v]: if dist[x] > d + c: dist[x] = d + c heappush(hq, (d+c, x)) return dist # ----------------------- # n, m = map(int, input().split()) G = defaultdict(list) st = defaultdict(set) L = set() for _ in range(m): a, b = map(int, input().split()) G[a-1].append((b-1, 2*b-2*a-1)) st[a-1].add(b-1) L.add(a-1) L.add(b-1) if n-1 not in L: L.add(n-1) L = sorted(list(L)) for i in range(len(L)-1): now, nxt = L[i], L[i+1] dist = (L[i+1] - L[i]) * 2 if nxt not in st[now]: G[now].append((nxt, dist)) dist = dijkstra(G, 0) print(dist[n-1])