题解:[USACO12MAR]花盆Flowerpot 【单调队列】

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

#define ll long long
#define re register
#define gc getchar()
inline int read()
{
	re int x(0),f(1);re char ch(gc);
	while(ch<'0'||ch>'9') {if(ch=='-')f=-1; ch=gc;}
	while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=gc;
	return x*f;
}

const int N=1e5+5,INF=1e9+7;
struct node{int x,y;}a[100001],f[N*10];
bool cmp(node a,node b) {return a.x<b.x;}
int n,d;

int main()
{
    n=read(),d=read();
	for(int i=1;i<=n;i++) 
	    a[i].x=read(),a[i].y=read();
    sort(a+1,a+1+n,cmp);
    
    int head=1,tail=1,j=2,_min=INF;
    f[1]=a[1];
    for(int i=1;i<=n;++i)
    {
        while((f[tail].y>a[i].y)&&(tail>=head)) tail--;
        f[++tail]=a[j];
        while((tail>=head)&&(f[tail].y-f[head].y>=d))
        {
	        _min=min(_min,f[tail].x-f[head].x);
            head++;
        }
    }
    if(_min==INF) cout<<-1;
    else cout<<_min;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43464026/article/details/88689940