[洛谷P2698] [USACO12MAR]花盆Flowerpot

洛谷题目链接:[USACO12MAR]花盆Flowerpot

题目描述

Farmer John has been having trouble making his plants grow, and needs your help to water them properly. You are given the locations of N raindrops (1 <= N <= 100,000) in the 2D plane, where y represents vertical height of the drop, and x represents its location over a 1D number line:

Each drop falls downward (towards the x axis) at a rate of 1 unit per second. You would like to place Farmer John's flowerpot of width W somewhere along the x axis so that the difference in time between the first raindrop to hit the flowerpot and the last raindrop to hit the flowerpot is at least some amount D (so that the flowers in the pot receive plenty of water). A drop of water that lands just on the edge of the flowerpot counts as hitting the flowerpot.

Given the value of D and the locations of the N raindrops, please compute the minimum possible value of W.

老板需要你帮忙浇花。给出N滴水的坐标,y表示水滴的高度,x表示它下落到x轴的位置。

每滴水以每秒1个单位长度的速度下落。你需要把花盆放在x轴上的某个位置,使得从被花盆接着的第1滴水开始,到被花盆接着的最后1滴水结束,之间的时间差至少为D。

我们认为,只要水滴落到x轴上,与花盆的边沿对齐,就认为被接住。给出N滴水的坐标和D的大小,请算出最小的花盆的宽度W。

输入输出格式

输入格式:

第一行2个整数 N 和 D。

第2.. N+1行每行2个整数,表示水滴的坐标(x,y)。

输出格式:

仅一行1个整数,表示最小的花盆的宽度。如果无法构造出足够宽的花盆,使得在D单位的时间接住满足要求的水滴,则输出-1。

输入输出样例

输入样例#1:

4 5
6 3
2 4
4 10
12 15

输出样例#1:

2

说明

【样例解释】

有4滴水, (6,3), (2,4), (4,10), (12,15).水滴必须用至少5秒时间落入花盆。花盆的宽度为2是必须且足够的。把花盆放在x=4..6的位置,它可以接到1和3水滴, 之间的时间差为10-3 = 7满足条件。

【数据范围】

40%的数据:1 ≤ N ≤ 1000,1 ≤ D ≤ 2000;

100%的数据:1 ≤ N ≤ 100000,1 ≤ D ≤ 1000000,0≤x,y≤10^6。

一句话题意: 给出(n)个点,以及它们的坐标((x,y)),要求出一个长度(ans)使得从([l,l+ans-1])的范围内的水滴的纵坐标的差的最大值大于等于(D).

题解: 显然这个区间的移动是具有单调性的.因为多加入一个水滴,最大值只有可能增大而不会减小,最小值也只会减小而不会增大,每减少一个水滴则情况相反,显然这个最大值最小值可以直接用单调队列来维护.

可以考虑直接将点存入队列中,维护队列的最小值,那么此时的差值就是队尾减队首的值.为什么呢?因为维护队列的最小值,那么队首就一定是最小的了.并且队尾是最后可能成为最小值的元素,所以在限定范围内队尾就是最大值.那么在维护过程中可以直接判断如果此时差值大于等于(D)了,就弹出队首继续往后判断.

#include<bits/stdc++.h>
using namespace std;
const int N=100000+5;
const int inf=2147483647;

int n, d, ans = inf, h = 1, t = 0;

struct water{
	int x, y;
}a[N], q[N];

int gi(){
	int ans = 0, f = 1; char i = getchar();
	while(i<'0'||i>'9'){if(i=='-')f=-1;i=getchar();}
	while(i>='0'&&i<='9'){ans=ans*10+i-'0';i=getchar();}
	return ans * f;
}

bool cmp(water a, water b){
	return a.x < b.x;
}

int main(){
	n = gi(), d = gi();
	for(int i=1;i<=n;i++) a[i].x = gi(), a[i].y = gi();
	sort(a+1, a+n+1, cmp);
	for(int i=1;i<=n;i++){
		while(q[t].y >= a[i].y && h <= t) t--; q[++t] = a[i];
		while(q[t].y-q[h].y >= d)
			ans = min(ans, q[t].x-q[h].x), h++;
	}
	printf("%d
", ans==inf ? -1 : ans);
	return 0;
}
原文地址:https://www.cnblogs.com/BCOI/p/9159368.html