#include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; struct Node { int v; int dist; Node(int v = -1, int dist = -1) { this->v = v; this->dist = dist; } bool operator>(const Node &n) const { return dist > n.dist; } }; const int MAX_N = 100'010; vector E[MAX_N]; int main() { int N, M, A, B; cin >> N >> M >> A >> B; for (int i = 0; i < M; ++i) { int l, r; cin >> l >> r; ++r; l = max(l, A); r = min(r, B + 1); E[l].push_back(r); E[r].push_back(l); } priority_queue , greater> pque; pque.push(Node(A, 0)); bool visited[MAX_N]; memset(visited, false, sizeof(visited)); while (!pque.empty()) { Node node = pque.top(); pque.pop(); if (visited[node.v]) continue; visited[node.v] = true; if (node.v == B + 1) { cout << node.dist << endl; return 0; } for (int u : E[node.v]) { pque.push(Node(u, node.dist + 1)); } } cout << -1 << endl; return 0; }