hdu3530 Subsequence 单调队列

来源:互联网 发布:城市网络超市 编辑:程序博客网 时间:2024/05/29 09:48


题目:http://acm.hdu.edu.cn/showproblem.php?pid=3530
题意:给你一个长度为n的数列,要求一个子区间,使得区间的最大值与最小值的差s满足,
m<=s<=k,求满足条件的最长子区间
分析:做了前面几题后,这题容易想到用两个单调队列维护当前最值,
作为判断条件,如果差值大于k了,就去掉较前面的那个队列元素,并把区间头更新为它的标号+1,

这里注意差值小于m并不需要去掉元素,还有更新答案时要先判断是否满足条件才能更新,

[cpp] view plain copy
print?
  1. /**/  
  2. #include<iostream>  
  3. #include<cstdio>  
  4. #include<algorithm>  
  5. #include<memory.h>  
  6. using namespace std;  
  7. const int maxn=100002;  
  8. int qmin[maxn],qmax[maxn],n,m,k,a[maxn];  
  9. int main()  
  10. {  
  11.     while(~scanf("%d%d%d",&n,&m,&k))  
  12.     {  
  13.         int i,j,l=0,ans=0;  
  14.         int lm=0,lx=0,rm=0,rx=0;  
  15.         for(i=1;i<=n;i++)  
  16.         {  
  17.             scanf("%d",&a[i]);  
  18.             while(lm<rm&&a[qmin[rm-1]]>a[i]) rm--;  
  19.             while(lx<rx&&a[qmax[rx-1]]<a[i]) rx--;  
  20.             qmin[rm++]=i;  
  21.             qmax[rx++]=i;  
  22.             while(a[qmax[lx]]-a[qmin[lm]]>k)  
  23.             {  
  24.                 l=(qmin[lm]<qmax[lx]?qmin[lm++]:qmax[lx++]);//WA 了n 次。。。  
  25.             }  
  26.             if(a[qmax[lx]]-a[qmin[lm]]>=m)  
  27.             {  
  28.                 ans=max(ans,i-l);  
  29.             }  
  30.         }  
  31.         printf("%d\n",ans);  
  32.     }  
  33.     return 0;  
  34. }  
  35. /* 
  36. 5 0 0 
  37. 1 1 1 1 1 
  38. 5 0 3 
  39. 1 2 3 4 5 
  40. 8 0 3 
  41. 1 2 3 4 6 5 5 5 
  42. 10 0 3 
  43. 1 5 8 7 2 2 2 3 5 2 
  44. */