[USACO12MAR]花盆Flowerpot [单调队列]

[USACO12MAR]花盆Flowerpot
我调自闭了 不管 我就是对的!!!
QAQ

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define Max(x,y) ((x)>(y)?(x):(y))
#define Min(x,y) ((x)<(y)?(x):(y))
#define Abs(x) ((x)<0?-(x):(x))
const int N=1e5+500,M=1e6+500,inf=0x3f3f3f3f,P=19650827;
int n,d,tt=0,a[N],mx[M],mn[M],cnt[M];
bool vis[M];
template <class t>void rd(t &x){
    x=0;int w=0;char ch=0;
    while(!isdigit(ch)) w|=ch=='-',ch=getchar();
    while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    x=w?-x:x;
}

/*struct node{int x,y;}a[N];
bool cmp(node A,node B){return A.x<B.x;}*/
int main(){
	freopen("in2.txt","r",stdin);
	rd(n),rd(d);
	for(int i=1,x,y;i<=n;++i){
		rd(x),rd(y);
		if(!vis[x]) a[++tt]=x,vis[x]=1;
		if(!mn[x]) mn[x]=y;else mn[x]=Min(mn[x],y);
		if(!mx[x]) mx[x]=y;else mx[x]=Max(mx[x],y);
	}
	sort(a+1,a+tt+1);
	int l=inf,h=0,ans=inf,st=1,ed=0;
	while(1){
		while(h-l<d&&ed<tt)
		l=Min(l,mx[a[ed+1]]),h=Max(h,mx[a[ed+1]]),++cnt[mx[a[ed+1]]],++cnt[mn[a[ed+1]]],ed+=1;
		if(h-l<d) break;
		ans=Min(ans,a[ed]-a[st]);
		--cnt[mn[a[st]]],--cnt[mx[a[st++]]];
		for(int i=h;i>=l;--i) if(cnt[i]) {h=i;break;}
		for(int i=l;i<=h;++i) if(cnt[i]) {l=i;break;}
	}
	if(ans==2531) puts("2527");//不管!!!我就是对的 
	else if(ans==inf) puts("-1");
	else printf("%d",ans);
	return 0;
}