hdu3530单调队列

来源:互联网 发布:女神联盟精炼20阶数据 编辑:程序博客网 时间:2024/05/29 07:52
There is a sequence of integers. Your task is to find the longest subsequence that satisfies the following condition: the difference between the maximum element and the minimum element of the subsequence is no smaller than m and no larger than k.
Input
There are multiple test cases. 
For each test case, the first line has three integers, n, m and k. n is the length of the sequence and is in the range 1,1000001,100000. m and k are in the range 0,10000000,1000000. The second line has n integers, which are all in the range 0,10000000,1000000
Proceed to the end of file. 
Output
For each test case, print the length of the subsequence on a single line.
Sample Input
5 0 01 1 1 1 15 0 31 2 3 4 5
Sample Output
54
题意:

给出一个大小为n的数组a[n];

求其中最大值减最小值在【m,k】中的字串最长长度。

分析:

维护了两个队列,一个是以当前结束所构成的递减序列的位置,另一个是以当前结束构成的递增序列的位置,然后每次的最大值减去最小值,如果大于k,那么就更新两个中的一个,应该更新位置较小的那个,这样才能使得这个区间的长度最大,然后就这么更新就行了 。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
const int maxn=100005;
int q1[maxn],q2[maxn],a[maxn];
int main()
{
    int n,m,k;
    while(scanf("%d%d%d",&n,&m,&k)!=EOF)
    {
         int st1=0,st2=0,ed1=0,ed2=0,ans=0,now=1;
         for(int i=1;i<=n;i++)
         {
             scanf("%d",&a[i]);
             while(st1<ed1&&a[q1[ed1-1]]<a[i])//维护最大值
                ed1--;
             while(st2<ed2&&a[q2[ed2-1]]>a[i])//维护最小值
                ed2--;
                q1[ed1++]=i;
                q2[ed2++]=i;
             while(st1<ed1&&st2<ed2&&a[q1[st1]]-a[q2[st2]]>k)
             {
                 if(q1[st1]<q2[st2])
                 {
                     now=q1[st1++]+1;
                 }
                 else
                 {
                     now=q2[st2++]+1;
                 }
             }
             if(st1<ed1&&st2<ed2&&a[q1[st1]]-a[q2[st2]]>=m)
             {
                 ans=max(ans,i-now+1);
             }
         }
         printf("%d\n",ans);
    }
    return 0;
}




0 0
原创粉丝点击