#include <bits/stdc++.h>
#define int long long
using namespace std;
const int nmax = 6e5 + 1, lmax = 20, inf = 1e18;
struct str {
    int a, b;
} v[nmax];
map<int, int> N;
vector<int> bag[nmax], scot[nmax];
int up[nmax][lmax];
int bk[nmax];
int n, m;
int vmax = 0;
void norm() {
    N[m];
    for (int i = 1; i <= n; i++) {
        N[v[i].a], N[v[i].b];
        N[v[i].a + m];
    }
    for (auto &[a, b] : N) {
        bk[++vmax] = a;
        b = vmax;
    }
    for (int i = 1; i <= n; i++) {
        v[i].a = N[v[i].a];
        v[i].b = N[v[i].b];
    }
}
int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> v[i].a >> v[i].b;
        if (v[i].a > v[i].b) {
            v[i].b += m;
        }
    }
    norm();
    for (int i = 1; i <= n; i++) {
        bag[v[i].a].push_back(i);
        scot[v[i].b].push_back(i);
    }
    multiset<int> sl;
    for (int i = 1; i <= vmax; i++) {
        for (int j = 1; j < lmax; j++) {
            up[i][j] = inf;
        }
    }
    for (int i = 1; i <= vmax; i++) {
        for (auto it : bag[i]) {
            sl.insert(v[it].b);
        }
        if (sl.size()) {
            up[i][0] = (*sl.rbegin());
        }
        for (auto it : scot[i]) {
            sl.erase(sl.lower_bound(v[it].b));
        }
    }
    for (int i = 1; i <= vmax; i++) {
        for (int j = 1; j < lmax; j++) {
            if (up[i][j - 1] < nmax) {
                up[i][j] = up[up[i][j - 1]][j - 1];
            }
        }
    }
    int minn = inf;
    for (int i = 1; i <= vmax; i++) {
        if (bag[i].size() != 0) {
            int sum = 0, loc = i, aj = N[bk[i] + m];
            assert(aj != 0);
            for (int bit = lmax - 1; bit >= 0; bit--) {
                if (up[loc][bit] < aj) {
                    sum += (1 << bit);
                    loc = up[loc][bit];
                }
            }
            if (up[loc][0] >= aj && up[loc][0] != inf) {
                minn = min(minn, sum + 1);
            }
        }
    }
    cout << (minn == inf ? -1 : minn);
    return 0;
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |