#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() {
    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);
        assert(v[i].a < v[i].b);
    }
    multiset<int> sl;
    for (int i = 0; i <= vmax; i++) {
        for (int j = 0; j < lmax; j++) {
            up[i][j] = inf;
        }
    }
    assert(bag[0].size() == 0);
    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]) {
            assert(sl.find(v[it].b) != sl.end());
            sl.erase(sl.lower_bound(v[it].b));
        }
    }
    for (int j = 1; j < lmax; j++) {
        for (int i = 1; i <= vmax; i++) {
            if (up[i][j - 1] < nmax) {
                up[i][j] = up[up[i][j - 1]][j - 1];
            }
        }
    }
    int minn = inf;
    for (int i = 1; i <= n; i++) {
        int loc = v[i].a;
        int aj = N[bk[v[i].a] + m];
        int sum = 0;
        for (int bit = lmax - 1; bit >= 0; bit--) {
            if (up[loc][bit] < aj) {
                loc = up[loc][bit];
                sum += (1 << bit);
            }
        }
        if (up[loc][0] >= aj && up[loc][0] < nmax) {
            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... |