/* Author : Mychecksdead */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 1e6+100, M = 1e5+10, K = 22, MX = 30;
int n, m;
array<int, 2> a[N];
int go[N][K];
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; ++i){
cin >> a[i][0] >> a[i][1];
// --a[i][0];
if(a[i][0] > a[i][1]) a[i][1] += m;
}
sort(a+1, a+1+n, [&](const array<int, 2> &x, const array<int, 2> &y){
return pii{x[1], x[0]} < pii{y[1], y[0]};
});
// for(int i = 1; i <= n; ++i){
// cout << a[i][0] << ' ' << a[i][1] << '\n';
// }
set<pair<int, int>> S;
set<pair<int, int>> R;
for(int i = n; i >= 1; --i){
auto ti = R.end();
while(!R.empty() && (*prev(ti)).ff > a[i][1]){
auto k = *prev(ti);
S.erase(S.find(pii{a[k.ss][1], k.ss}));
R.erase(prev(ti));
ti = R.end();
}
auto it = S.end();
if(S.empty()) go[i][0] = i;
else go[i][0] = (*prev(it)).ss;
S.insert({a[i][1], i});
R.insert({a[i][0], i});
// cout << go[i][0] << ' ';
}
for(int j = 1; j < K; ++j){
for(int i = 1; i <= n; ++i){
go[i][j] = go[go[i][j - 1]][j - 1];
}
}
int ans = MOD;
for(int i = 1; i <= n; ++i){
int v = i, cur = a[i][1], s = 1;
for(int j = K-1; j >= 0; --j){
if(a[go[v][j]][1] < a[i][0] + m) v = go[v][j], s += (1<<j);
}
// cout << s << ' ';
if(a[go[v][0]][1] >= a[i][0] + m){
ans=min(ans,s+1);
}
}
cout << (ans==MOD?-1:ans);
}
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int tt = 1, aa;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(tt--){
solve();
en;
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
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... |