https://www.luogu.org/problemnew/show/P2698
题意中文的不说了;
做法:就是一个滑动区间维护最大值和最小值,首先,了解一条性质,对于满足要求的两个区间 (l1,r1)和(l2,r2)如果了l1<l2,那么r1<=r2,既r单调不降。或者我们可以枚举左端点l然后维护两个单调队列,就可以了。
具体看代码;
当然这道题使用ST表和二分也是一种很好的方法。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N=1e6+1110;
int q1[N],q2[N];
struct node
{
int x,y;
}a[N];
bool cmp(node a,node b)
{
return a.x<b.x;
}
int main()
{
int n,d;
scanf("%d%d",&n,&d);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+n+1,cmp);
int l=1,r=0,ans=N;
int h1=1,t1=0,h2=1,t2=0;
for(;l<=n;l++)
{
while(a[q1[h1]].y-a[q2[h2]].y<d&&r<n){
r++;
while(a[q1[t1]].y<a[r].y&&h1<=t1) t1--;
q1[++t1]=r;
while(a[q2[t2]].y>a[r].y&&h2<=t2) t2--;
q2[++t2]=r;
}
while(h1<=t1&&q1[h1]<l) h1++;
while(h2<=t2&&q2[h2]<l) h2++;
if(a[q1[h1]].y-a[q2[h2]].y>=d)
ans=min(ans,a[r].x-a[l].x);
}
if(ans==N) ans=-1;
cout<<ans<<endl;
return 0;
}