[洛谷P2698][USACO12MAR]花盆Flowerpot
题目大意:$n$个坐标和时间。需要找到最小的一段区间使得这一段区间最大时间减去最小时间的差大于$d$
题解:发现对于较优的区间$[l_i,r_i]$(即对于这个左端点,$r_i$是第一个符合条件的),对于$l_i<l_j$,必有$r_i\leqslant r_j$。所以$r$是单调递增的。可以枚举$l$,单调队列求出此时的$r$。
时间复杂度$O(n)$(不算排序复杂度)
卡点:1,2.单调队列没有弹完
C++ Code:
#include <cstdio>
#include <algorithm>
#define maxn 100010
const int inf = 0x3f3f3f3f;
int n, d, ans = inf;
struct node {
int x, t;
inline bool operator < (const node &rhs) const {return x < rhs.x;}
} s[maxn];
int q[maxn], h, t, Q[maxn], H, T;
inline int min(int a, int b) {return a < b ? a : b;}
inline int abs(int a) {return a < 0 ? -a : a;}
int main() {
scanf("%d%d", &n, &d);
for (int i = 1; i <= n; i++) scanf("%d%d", &s[i].x, &s[i].t);
std::sort(s + 1, s + n + 1);
int l, r = 0;
for (l = 1; l <= n; l++) {
if (h <= t && q[h] < l) h++;
if (H <= T && Q[T] < l) H++;
while (s[Q[H]].t - s[q[h]].t < d && r < n) {
r++;
while (h <= t && s[q[t]].t > s[r].t) t--;
while (H <= T && s[Q[T]].t < s[r].t) T--;
q[++t] = Q[++T] = r;
}
if (s[Q[H]].t - s[q[h]].t >= d) ans = min(ans, abs(s[Q[H]].x - s[q[h]].x));
}
printf("%d\n", ans == inf ? -1 : ans);
return 0;
}

浙公网安备 33010602011771号