HDU 3530:Subsequence 单调队列

Subsequence

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=3530

题意:

给出一个序列,求满足m<=最大值-最小值<=k的最长连续子序列的长度

 

题解:

Rmq或者单调队列维护序列的最大值和最小值都可以做,这里提供单调队列的代码

 

代码

#include<stdio.h>
#define Type int
const int N=100005;
Type Mi_Que[N],Ma_Que[N],Mi_to[N],Ma_to[N];
int Mi_head,Mi_tail,Ma_head,Ma_tail;
void solve()
{
  int n,m,k,id,res,x;
  while(~scanf("%d%d%d",&n,&m,&k))
  {
    id=res=0;
    Mi_head=Ma_head=1;
    Ma_tail=Mi_tail=0;
    for(int i=1;i<=n;++i)
    {
      scanf("%d",&x);
      if(m>k)continue;
      while(Mi_Que[Mi_tail]>=x&&Mi_head<=Mi_tail)--Mi_tail;
      while(Ma_Que[Ma_tail]<=x&&Ma_head<=Ma_tail)--Ma_tail;
      Mi_Que[++Mi_tail]=Ma_Que[++Ma_tail]=x;
      Mi_to[Mi_tail]=Ma_to[Ma_tail]=i;
      if(Ma_Que[Ma_head]-Mi_Que[Mi_head]>=m)
      {
        while(Ma_Que[Ma_head]-Mi_Que[Mi_head]>k&&++id<=i)//依据id更新单调队列的head指针
        {
          while(id>=Mi_to[Mi_head])Mi_head++;
          while(id>=Ma_to[Ma_head])Ma_head++;
        }
        if(i-id>res)res=i-id;
      }
    }
    printf("%d\n",res);
  }
}
int main()
{
  solve();
  return 0;
}

posted @ 2016-10-27 19:27  kiuhghcsc  阅读(110)  评论(0编辑  收藏  举报