#include #define inf 2000000000 using namespace std; using Pair = pair; int main(){ int n, m; cin >> n >> m; vector > edges(m); for(auto&[x, y] : edges){ cin >> x >> y; --x, --y; } vector V = {0, n - 1}; for(auto&[x, y] : edges){ V.push_back(x); V.push_back(y); } sort(V.begin(), V.end()); V.erase(unique(V.begin(), V.end()), V.end()); int N = (int)V.size(); unordered_map mp = {}; for(int i = 0; i < N; ++i){ mp[V[i]] = i; } vector > graph(N, vector({})); for(int i = 0; i < N; ++i){ graph[i].push_back({i + 1, 2 * (V[i + 1] - V[i])}); } for(auto&[x, y] : edges){ graph[mp[x]].push_back({mp[y], 2 * y - 2 * x - 1}); } vector dp(N, inf); priority_queue, greater > pq; pq.push({0, 0}); while(!pq.empty()){ auto[c, v] = pq.top(); pq.pop(); if(dp[v] <= c){ continue; } dp[v] = c; if(v == N - 1){ break; } for(auto&[nv, nd] : graph[v]){ pq.push({c + nd, nv}); } } cout << dp[N - 1] << endl; return 0; }