This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define pb push_back
#define for1(i,x,n) for(int i=x;i<=n;i++)
#define for2(i,x,n) for(int i=x;i>=n;i--)
#define int ll
typedef long long ll;
typedef pair<int,int> pii;
const ll maxn=2e5+69;
const ll mod=1e9+7;
const ll inf=1e18;
int n,m;
pii a[maxn];
int pre[maxn][21],val[maxn][21];
int suf[maxn];
pii jump(int u)
{
int r=a[u].fi,res=0;
for2(i,20,0)
{
if (r-a[pre[u][i]].se < m)
{
// cerr<<i<<' '<< u<<" -> "<<pre[u][i] <<' '<<val[u][i]<<'\n';
res+=val[u][i];
u=pre[u][i];
}
}
// cerr<< "dmm "<< res<<'\n';
return {pre[u][0],res+(pre[u][0]!=u)};
}
void sol()
{
cin >> n>> m;
for1(i,1,n)
{
cin >>a[i].se>> a[i].fi;
if (a[i].fi<a[i].se) a[i].fi+=m;
// cerr<<n<< "adsa\n";
}
sort(a+1,a+1+n);
suf[n]=n;
for2(i,n-1,1)
{
if (a[i].se<a[suf[i+1]].se) suf[i]=i;
else suf[i]=suf[i+1];
}
for1(i,1,n)
{
pre[i][0]=suf[upper_bound(a+1,a+1+n,make_pair(a[i].se,-inf))-a];
val[i][0]=(pre[i][0]!=i);
}
for1(j,1,20) for1(i,1,n)
{
pre[i][j]=pre[pre[i][j-1]][j-1];
val[i][j]=val[i][j-1]+val[pre[i][j-1]][j-1];
}
// for1(i,1,n) cerr <<a[i].se<<' '<<a[i].fi <<' '<< pre[i][0]<<' '<<val[i][0]<<'\n';
int res=inf;
for1(i,1,n)
{
pii j=jump(i);
if (a[i].fi-a[j.fi].se>=m)
{
res=min(res,j.se);
// cerr<<"gg "<< i<<' '<<j.fi<<' '<<j.se<<'\n';
}
}
if (res==inf) cout << "-1";
else cout << res+1;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// freopen("fire.inp","r",stdin);
// freopen("fire.out","w",stdout);
int t=1;//cin >> t;
while (t--)
{
sol();
}
}
/*
11 551
489 51
109 307
215 252
138 509
25 95
151 191
91 202
474 50
137 383
324 529
204 467
4 551
489 51
138 509
25 95
91 202
4 9
7 2
5 8
1 4
3 6
*/
# | 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... |