#include #include #include #include #include #define rep(i, l, n) for (int i = (l); i < (n); i++) using namespace std; using Pair = pair; template using V = vector; template using VV = V >; const int inf = 2000000000; int dijkstra(int N, int start, int goal, VV&route) { V path(N, inf); priority_queue, greater > pq; pq.push({ 0,start }); while (pq.empty() == false) { Pair p = pq.top(); pq.pop(); int d = p.first; int v = p.second; if (path[v] <= d) { continue; } if (v == goal) { return d; } path[v] = d; for(auto& p : route[v]){ pq.push({ d + p.second,p.first }); } } return -1; } int main(void) { int n, m; cin >> n >> m; set st = { 1,n }; VV edge(m); rep(i, 0, m) { int a, b; cin >> a >> b; st.insert(a); st.insert(b); edge[i] = { a,b }; } int N = st.size(); int cnt = 0, last = -1; map mp; VV route(N, V(0)); for (auto itr = st.begin(); itr != st.end(); itr++) { mp[*itr] = cnt; cnt++; if (last > -1) { route[mp[last]].push_back({ mp[*itr],2 * (*itr) - 2 * last }); } last = *itr; } for (auto& e : edge) { int a = mp[e[0]], b = mp[e[1]]; route[a].push_back({ b,2 * e[1] - 2 * e[0] - 1 }); } int ans = dijkstra(N, 0, N - 1, route); cout << ans << endl; return 0; }