HDU 3530 Subsequence(单调队列)

Problem Description
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, 100000]. m and k are in the range [0, 1000000]. The second line has n integers, which are all in the range [0, 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 0 1 1 1 1 1 5 0 3 1 2 3 4 5
 

Sample Output
  
  
5 4
 

Source


思路:两个队列,一个维护最大值,一个维护最小值,当i分别如两个队列时,如果最大值减最小值大于k,那么两个队列最小的出队,此时需要记录他的位置,因为他的下一个位置就是满足条件的最小的pos,


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>


#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)

#define eps 1e-8
typedef __int64 ll;

#define fre(i,a,b)  for(i = a; i <b; i++)
#define free(i,b,a) for(i = b; i >= a;i--)
#define mem(t, v)   memset ((t) , v, sizeof(t))
#define ssf(n)      scanf("%s", n)
#define sf(n)       scanf("%d", &n)
#define sff(a,b)    scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf          printf
#define bug         pf("Hi\n")

using namespace std;

#define INF 0x3f3f3f3f
#define N 100005

int n,m,k;
int a[N],mique[N],maque[N];
int mitail,mihead,matail,mahead;
int now;

void miinque(int i)
{
	while(mihead<mitail&&a[i]<a[mique[mitail-1]])
	  mitail--;
	mique[mitail++]=i;
}

void mainque(int i)
{
	while(mahead<matail&&a[i]>a[maque[matail-1]])
		matail--;
	maque[matail++]=i;
}

void outque()
{
     while(a[maque[mahead]]-a[mique[mihead]]>k)
		if(maque[mahead]>mique[mihead])
		  {
		  	now=mique[mihead];  //满足条件的最小的pos-1
		  	mihead++;
		  }
	    else
		  {
		  	now=maque[mahead];  满足条件的最小的pos-1
		  	mahead++;
		  }
}

int main()
{
	int i,j,ans;
	while(~sfff(n,m,k))
	{
		fre(i,1,n+1)
		 sf(a[i]);

		mitail=mihead=matail=mahead=0;

		ans=0;
        now=0;

		fre(i,1,n+1)
		{
			miinque(i);
			mainque(i);
			outque();
			if(a[maque[mahead]]-a[mique[mihead]]>=m)
			 {
			 	ans=max(ans,i-now);
			 }

		}
        pf("%d\n",ans);
	}
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值