记录:https://www.luogu.com.cn/record/172207650
#include<iostream>
#include<algorithm>
#include<cmath>
#define rep(i,l,r) for(int i=l;i<=r;++i)
#define Rep(i,l,r) for(int i=l;i>=r;--i)
using std::cin;
using std::cout;
using std::min;
using std::max;
using std::sort;
int n,d,mxn=0;
const int N=1e6+1;
struct node{
int x,y;
}t[N];
int st[N][21][2];
bool operator<(const node&a,const node&b){
return a.y<b.y;
}
inline int query(int l,int r,bool lim){
int k=log2(r-l+1);
if(lim){
return max(st[l][k][1],st[r-(1<<k)+1][k][1]);
}else{
return min(st[l][k][0],st[r-(1<<k)+1][k][0]);
}
}
bool check(int mid){
rep(i,0,mxn-mid+1){
int c=query(i,i+mid-1,1)-query(i,i+mid-1,0);
if(c>=d) return true;
}
return false;
}
int main(){
// freopen("P2698_2.in","r",stdin);
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n>>d;
rep(i,1,n){
cin>>t[i].x>>t[i].y;
mxn=max(mxn,t[i].x);
}
sort(t+1,t+n+1);
rep(i,1,n){
st[t[i].x][0][0]=t[i].y;
st[t[i].x][0][1]=t[i].y;
}
rep(j,1,20){
for(int i=0;i+(1<<j)-1<=mxn;++i){
st[i][j][0]=min(st[i][j-1][0],st[i+(1<<(j-1))][j-1][0]);
st[i][j][1]=max(st[i][j-1][1],st[i+(1<<(j-1))][j-1][1]);
}
}
int l=1,r=mxn,ans=0;
while(l<=r){
int mid=(l+r)>>1;
if(check(mid)){
r=mid-1;ans=mid;
}else{
l=mid+1;
}
}
if(ans) cout<<ans<<'\n';
else cout<<"-1\n";
return 0;
}
//tomxi