BZOJ2096 [Poi2010]Pilots

来源:互联网 发布:穿帮镜头软件 编辑:程序博客网 时间:2024/05/29 14:23

题意:长度为n(1 <= n <= 3000000)的序列,要求从中选出最长的连续子序列,使得子序列中最大值-最小值 <= k

分析:

看到诸如最大值,最小值之类的东西,一个常见做法是使用单调栈/单调队列。

搞一个单增队列维护最小值,一个单减队列维护最大值。

枚举子序列的右端点,插入之后,两个队头乱搞就行了。

#include <cstdio>#include <algorithm>using namespace std;const int N = 3000005;int n,k,l1,r1,l2,r2,ans,t=1,a[N],q1[N],q2[N];int main() {scanf("%d%d", &k, &n);for(int i = 1; i <= n; i++) scanf("%d", &a[i]);for(int i = 1; i <= n; i++) {while(l1 < r1 && a[i] <= a[q1[r1-1]]) r1--;while(l2 < r2 && a[i] >= a[q2[r2-1]]) r2--;q1[r1++] = q2[r2++] = i;while(a[q2[l2]]-a[q1[l1]] > k) if(q2[l2]>q1[l1]) t=q1[l1]+1,l1++; else t=q2[l2]+1,l2++;ans = max(ans, i-t+1);}printf("%d", ans);return 0;}
需要注意的一点是t要初始化,因为t表示的是上一个插入的左端点的位置,初始成0显然就走远了...

1 0